【问题标题】:JSON to CSV export using PHP使用 PHP 将 JSON 导出为 CSV
【发布时间】: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 我从开发人员那里得到了这段代码,他让我做一些改变,但我做不到,所以它没有解决问题。

标签: php json csv


【解决方案1】:

查看json_decode function 以解码 json 数据。

对于 CSV 生成,您可以“手动”形成它(这只是写在一个文件中),但使用一些现有的库当然更好,比如非凡包联盟提出的库(多么好的名字!:) ) : http://csv.thephpleague.com/.

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2020-09-23
    • 2019-07-24
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多