【发布时间】:2015-09-08 16:01:40
【问题描述】:
我们使用的营销应用程序为我提供了以下 JSON 代码,我想将其导出为 CSV 文件。
{"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));
}
?>
【问题讨论】:
-
@JonStirling 我添加了我正在使用的代码。我尝试了 2 种不同的代码。
-
好的,下一个问题。实际发生了什么,你期望发生什么。顺便说一句,我不知道你到底想用
array_merge做什么。 -
抱歉@JonStirling 我从开发人员那里得到了这段代码,他让我做一些改变,但我做不到,所以它没有解决问题。