PHP JSON到带有标头的csv


PHP JSON to csv with headers

我收到了来自cURL帖子的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":[]}

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

要查看从类似json的字符串转换为数组/对象的内容:

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

得出以下结果:

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);

这是执行print_r:后的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);