带标题的PHP JSON到csv

带标题的PHP JSON到csv,php,json,csv,curl,Php,Json,Csv,Curl,我从一个cURL post接收JSON,它看起来如下所示: {"status":"ok","sent":177,"delivered":0,"bounced":5,"hardBounced":0,"softBounced":5,"opened":[46,81],"clicked":[5,5],"notsent":[2,2],"notopened":126,"optout":0,"spam":0,"lastOpen":"1 day ago","lastClick":"13 days ago","l

我从一个cURL post接收JSON,它看起来如下所示:

{"status":"ok","sent":177,"delivered":0,"bounced":5,"hardBounced":0,"softBounced":5,"opened":[46,81],"clicked":[5,5],"notsent":[2,2],"notopened":126,"optout":0,"spam":0,"lastOpen":"1 day ago","lastClick":"13 days ago","lastOpenTS":1459808038636,"lastClickTS":1458752521593,"rebroadcast":0,"rebroadcastClick":0,"msgId":"s-04ac-1603","subject":"Blah blah Conference and Exposition","title":"Blah followup 03.22.16","sentto":["l-160f"],"suppressedon":[]}
Array
(
[status] => ok
[sent] => 177
[delivered] => 0
[bounced] => 5
[hardBounced] => 0
[softBounced] => 5
[opened] => Array
    (
        [0] => 46
        [1] => 81
    )

[clicked] => Array
    (
        [0] => 5
        [1] => 5
    )

[notsent] => Array
    (
        [0] => 2
        [1] => 2
    )

[notopened] => 126
[optout] => 0
[spam] => 0
[lastOpen] => 1 day ago
[lastClick] => 14 days ago
[lastOpenTS] => 1459808038636
[lastClickTS] => 1458752521593
[rebroadcast] => 0
[rebroadcastClick] => 0
[msgId] => s-04ac-1603
[subject] => AFSA Vehicle Finance Conference and Exposition
[title] => AFSA follow up 03.22.16
[sentto] => Array
    (
        [0] => l-160f
    )

[suppressedon] => Array
    (
    )

)
我正在编辑原始帖子,以在评论的帮助下显示进展:

要查看从类似json的字符串转换为数组/对象的内容,请执行以下操作:

$result = curl_exec($ch_list);
$jsonObj = print_r(json_decode($result, true));
var_dump($jsonObj);die();
其结果如下:

{"status":"ok","sent":177,"delivered":0,"bounced":5,"hardBounced":0,"softBounced":5,"opened":[46,81],"clicked":[5,5],"notsent":[2,2],"notopened":126,"optout":0,"spam":0,"lastOpen":"1 day ago","lastClick":"13 days ago","lastOpenTS":1459808038636,"lastClickTS":1458752521593,"rebroadcast":0,"rebroadcastClick":0,"msgId":"s-04ac-1603","subject":"Blah blah Conference and Exposition","title":"Blah followup 03.22.16","sentto":["l-160f"],"suppressedon":[]}
Array
(
[status] => ok
[sent] => 177
[delivered] => 0
[bounced] => 5
[hardBounced] => 0
[softBounced] => 5
[opened] => Array
    (
        [0] => 46
        [1] => 81
    )

[clicked] => Array
    (
        [0] => 5
        [1] => 5
    )

[notsent] => Array
    (
        [0] => 2
        [1] => 2
    )

[notopened] => 126
[optout] => 0
[spam] => 0
[lastOpen] => 1 day ago
[lastClick] => 14 days ago
[lastOpenTS] => 1459808038636
[lastClickTS] => 1458752521593
[rebroadcast] => 0
[rebroadcastClick] => 0
[msgId] => s-04ac-1603
[subject] => AFSA Vehicle Finance Conference and Exposition
[title] => AFSA follow up 03.22.16
[sentto] => Array
    (
        [0] => l-160f
    )

[suppressedon] => Array
    (
    )

)
在这一点上,我想好了,我已经把它转换成一个数组,这应该会导致创建csv文件,我可以使用大家在很多帖子中推荐的代码,我确实收到了一个错误,但是在fopen之后的if语句纠正了这个错误。 现在,它正在创建一个csv文件,其中没有任何内容:

$result = curl_exec($ch_list);
$jsonObj = print_r(json_decode($result));

if(!file_exists('/tmp/' . $msgId . '_' . $yearMonComb . '.csv')) {
    $f = fopen('/tmp/' . $msgId . '_' . $yearMonComb . '.csv', 'w');
    if (is_array($jsonObj) || is_object($jsonObj)) {
        $firstLineKeys = false;
        foreach ($jsonObj as $line) {
            if (empty($firstLineKeys)) {
                $firstLineKeys = array_keys($line);
                fputcsv($f, $firstLineKeys);
                $firstLineKeys = array_flip($firstLineKeys);
            }
            fputcsv($f, array_merge($firstLineKeys, $line));
        }
    }
    fclose($f);
}

您可能想要的是:

$result = curl_exec($ch_list);
// Decode the JSON representation into PHP data structures
// The second argument asks to return arrays (TRUE), not objects (FALSE or missing)
$data = json_decode($result, true);

$f = fopen($filename, 'w');

// Header line: the field names (keys in $data)
fputcsv($f, array_keys($data), ',');
// Data line (can use array_values($data) or just $data as the 2nd argument)
fputcsv($f, array_values($data), ',');

fclose($f);

在一位同事的帮助下,根据你们中一些人的评论,以下是对我的情况有效的方法:

$result = curl_exec($ch_list);
$jsonObj = json_decode($result, true);

$f = fopen('/tmp/' . $msgId . '_' . $yearMonComb . '.csv', 'w');
fputcsv($f, array_keys($jsonObj));
$transposed = array();

if (is_array($jsonObj)) {
    foreach($jsonObj as $key => $record){
        if(is_array($record) && count($record) > 0){
            $target = count($record) - 1;
            $transposed[$key] = $jsonObj[$key][$target];
        }else{
            $transposed[$key] = $record;
        }
    }
    fputcsv($f, array_values($transposed));
}
fclose($f);

echo $result;
curl_close($ch_list);
这是打印后的json数据:

Array
(
[status] => ok
[sent] => 177
[delivered] => 0
[bounced] => 5
[hardBounced] => 0
[softBounced] => 5
[opened] => Array
    (
        [0] => 46
        [1] => 81
    )

[clicked] => Array
    (
        [0] => 5
        [1] => 5
    )

[notsent] => Array
    (
        [0] => 2
        [1] => 2
    )

[notopened] => 126
[optout] => 0
[spam] => 0
[lastOpen] => 1 day ago
[lastClick] => 14 days ago
[lastOpenTS] => 1459808038636
[lastClickTS] => 1458752521593
[rebroadcast] => 0
[rebroadcastClick] => 0
[msgId] => s-04ac-1603
[subject] => Blah blah Conference and Exposition
[title] => Blah blah follow up 03.22.16
[sentto] => Array
    (
        [0] => l-160f
    )

[suppressedon] => Array
    (
    )

)
结果是一个398字节的csv文件

以数组的值为数组的情况回答@axiac的问题。数组的条件测试:

if(is_array($record) && count($record) > 0)
如果存在数组,则获取数组的最后一个元素

我希望这能帮助别人,因为这让我发疯

另一个编辑是因为我找到了一种循环遍历数组的方法

我创建了一个单独的php文件来收集数组中的数组项,数组位于父数组的$jsonObj['result']项中

        $jsonObj = json_decode($result, true);
        $f = fopen($value . '-sent.csv', 'w');

        $headers = array('listid', 'name', 'when', 'recid', 'email', 'ts');

        if (is_array($jsonObj)) {
            fputcsv($f, $headers);
            foreach ($jsonObj['result'] as $fields) {
                fputcsv($f, $fields);
            }
        }
        fclose($f);

        curl_close($ch_list);

请发布
print\r($strtar)
的输出,这样我们就可以准确地看到您传递到
fputcsv()
(这应该是一个简单的一维数组)中的内容
json\u encode()
json\u decode()
中的嵌套有点可疑-
$result
的原始内容是什么?请同时发布
var\u dump($result)
。如果它不是可以编码为json的东西,那么它将返回
false
,而
json\u decode()
反过来将不会产生可由
fputcsv()
使用的东西。print\r($strtarr)产生与print\r(结果)相同的结果。我想我根本没有制作数组,所以你的意思是说
$strtarr
包含一个JSON字符串?这就是问题所在,因为
fputcsv()
通过输入数组以CSV列的形式写入CSV。我已经取出了json_编码,我可以看到一个数组-ty-让我再次尝试运行该文件仍然会生成一个空文件我发布的代码不会做任何错误处理。你应该这样做。可能
$result
FALSE
(因为HTTP请求失败)。我用您发布的JSON(而不是调用
curl\u exec()
)尝试了一下,效果很好。除了从JSON解码的数组包含一些键的数组(它们不能以CSV格式表示)这一事实之外,是的,在我偶然发现这些其他问题之前,我考虑过这一点-我将如何处理数组中的数组。我尝试只回显$result并使用javascript处理它,但是我无法创建csv文件。它快把我逼疯了