PHP 库将 JSON 转换为 CSV?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9573421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:09:21  来源:igfitidea点击:

PHP Library to convert JSON to CSV?

phpjsoncsvdata-export

提问by wajiw

I've got a JSON service and need to create a script to export data to CSV files. Does anyone have a method or library you can suggest to migrate JSON to CSV format?

我有一个 JSON 服务,需要创建一个脚本来将数据导出到 CSV 文件。有没有人可以建议将 JSON 迁移到 CSV 格式的方法或库?

Here's an example format though I expect to have to retro-fit the solution to work with it:

这是一个示例格式,但我希望必须改进解决方案才能使用它:

{"service_name":
      { key : value, key : value....}
}

or:

或者:

{"service_name":
        [
               { key : value, key : value....},
               ...
         ]
}

回答by mindandmedia

i generally agree with the commenters, but if you're data is prepared this way, isn't this pseudo-code all you need?

我通常同意评论者的意见,但是如果您的数据是这样准备的,那么您只需要这个伪代码吗?

$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}";

$json_obj = json_decode ($json_str);

$fp = fopen('file.csv', 'w');

foreach ($json_obj as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

回答by curtisdf

Something like this should work, assuming your JSON is an array of data sets without arrays or embedded objects:

假设您的 JSON 是一个没有数组或嵌入对象的数据集数组,这样的事情应该可以工作:

$file = file_get_contents('http://example.com/blah/blah');
$json = json_decode($file);

$csvfile = fopen('file.csv', 'w+');
foreach ($json as $row) {
    $line = "'" . join("\",\"", $row) . "\"\n";
    fputs($csvfile, $line);
}
fclose($csvfile);

You'll have to add appropriate error handling. There are a lot of things that can go wrong when trying to do this sort of thing (i.e. JSON file not available or is malformatted, can't create new CSV file)

您必须添加适当的错误处理。尝试执行此类操作时可能会出现很多问题(即 JSON 文件不可用或格式错误,无法创建新的 CSV 文件)

回答by Kostanos

I just needed to do the same. I wrote the small command line script, which take as a parameter the json file and output the CSV.

我只需要做同样的事情。我写了一个小的命令行脚本,它将json文件作为参数并输出CSV。

You can check it here: PHP Converting JSON array to CSV

您可以在这里查看:PHP Converting JSON array to CSV

The important staff there is using keys of array as the first row in CSV file. And maintaining the order on the next elements, to not mess up the CSV.

那里的重要人员使用数组的键作为 CSV 文件的第一行。并保持下一个元素的顺序,以免弄乱 CSV。

Here is the code:

这是代码:

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

回答by Burak

I've run into this issue multiple times; that's why I created a library called ozdemirburak/json-csv, which can convert JSON to CSV and vice versa; thus, it can handle nested structure.

我多次遇到这个问题;这就是为什么我创建了一个名为ozdemirburak/json-csv的库,它可以将 JSON 转换为 CSV,反之亦然;因此,它可以处理嵌套结构。

$ composer require ozdemirburak/json-csv

To use it:

要使用它:

use OzdemirBurak\JsonCsv\File\Json;

$json = new Json($inputFilePath);
$csvString = $json->convert();
// you can also save the CSV string to a file.
$json->convertAndSave($outputFilePath);