使用PHP将JSON导出为CSV

时间:2015-09-08 16:01:41

标签: php json csv

我们正在使用的营销应用程序为我提供了以下我想要导出为CSV文件的JSON代码。

{"FirstName":"data","Surname":"data","E-mail Address":"data","PurchasedGoods":"data","Address1":"data","Address2":"data","City":"data","Postcode":"data","Company":"data","MiddleName":"data","Country":"data","Title":"data"}

JSON代码中会有很多记录。

请帮助我使用可以将上述JSON代码/记录导出到CSV文件的PHP代码。

我目前正在使用以下代码:

<?php
$request = file_get_contents('php://input');
$req_dump = print_r($request, TRUE);
$fp = fopen('request.log', 'a');
$fp = fopen('file.csv', 'w');
fwrite($fp, $req_dump);
fclose($fp);
?>

我还添加了以下代码但没有快乐:

#!/usr/bin/php
<?php


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('php://output', 'w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    // Using array_merge is important to maintain the order of keys acording to the first element
    fputcsv($f, array_merge($firstLineKeys, $line));
}
?>

1 个答案:

答案 0 :(得分:0)

查看json_decode function以解码json数据。

对于CSV生成,你可以“手动”形成它(这只是写在一个文件中),但是使用一些现有的librairies肯定会更好,比如Extraordinary Packages联盟提出的那个(什么名字!:) ):http://csv.thephpleague.com/

希望有所帮助。

相关问题