使用PHP将JSON转换为CSV格式

前端之家收集整理的这篇文章主要介绍了使用PHP将JSON转换为CSV格式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 PHP脚本将json文件转换为csv格式.代码如下:
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];

$json = file_get_contents($jsonFilename);
$array = json_decode($json,true);
$f = fopen('output.csv','w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
            $firstLineKeys = array_keys($line);
            fputcsv($f,$firstLineKeys);
            $firstLineKeys = array_flip($firstLineKeys);
    }

fputcsv($f,array_merge($firstLineKeys,$line));

}

这种工作,但只返回JSON文件的外部变量,并且我得到一个“数组到字符串转换”警告

JSON数据如下所示:

{"type":"NON_ATTRIBUTED","conversion":{,"value_1":"000000100355321","value_3":"XXXX","value_4":"12667","value_5":"6"},"stream_type":"COOKIE"}
{"type":"ATTRIBUTED","value_1":"000000167865321","value_3":"YYYY","value_4":"12668","value_5":"0"},"stream_type":"COOKIE"}
{"type":"NON_ATTRIBUTED","value_1":"000000134535321","value_3":"AAAA","value_4":"12669","value_5":"9"},"value_1":"000000100357651","value_3":"WWWW","value_4":"12670","value_5":"2"},"stream_type":"COOKIE"}

我得到的输出是:
类型,转换,的stream_type
NON_ATTRIBUTED,阵列,COOKIE
NON_ATTRIBUTED,COOKIE

我期望的输出是:
类型,value_1,value_3,value_4,value_5,stream_type
NON_ATTRIBUTED,000000100355321,XXXX,1267,6,COOKIE
..

任何帮助赞赏,因为这对我来说非常新鲜

json_decode($json,true);将JSON对象转换为关联数组.所以这
{
    "type":"NON_ATTRIBUTED","value_5":"6"
    },"stream_type":"COOKIE"
}

成为这个:

array(3) { 
    ["type"]=> string(14) "NON_ATTRIBUTED" 
    ["conversion"]=> array(4) { 
        ["value_1"]=> string(15) "000000100355321" 
        ["value_3"]=> string(4) "XXXX" 
        ["value_4"]=> string(5) "12667" 
        ["value_5"]=> string(1) "6" 
    } 
    ["stream_type"]=> string(6) "COOKIE" 
}

你看到有嵌套数组.并且您试图将数组的所有元素插入到您的文本文件(csv只是一个简单的文本文件)与此行:

fputcsv($f,$line));

当数组的元素是字符串时,它工作得很好.但是当元素是数组时,我们得到了数组来转换字符串.所以你必须在嵌套数组中使用loop或array_merge来防止这种情况.

我不清楚你的csv是如何看起来的,但是我希望你的代码能够帮助你.如果没有,请在下面写下评论.

if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];

$json = file_get_contents($jsonFilename);
$array = json_decode($json,'w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f,$firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    $line_array = array($line['type']);
    foreach ($line['conversion'] as $value)
    {
        array_push($line_array,$value);
    }
    array_push($line_array,$line['stream_type']);
    fputcsv($f,$line_array);

}

你的json还有一个错误 – 不必要的逗号:“conversion”:{,

猜你在找的PHP相关文章