使用 PHP 将 CSV 转换为 JSON?
我需要使用 PHP 在服务器上将 CSV 文件转换为 JSON。我正在使用这个有效的脚本:
function csvToJSON($csv) {
$rows = explode("\n", $csv);
$i = 0;
$len = count($rows);
$json = "{\n" . ' "data" : [';
foreach ($rows as $row) {
$cols = explode(',', $row);
$json .= "\n {\n";
$json .= ' "var0" : "' . $cols[0] . "\",\n";
$json .= ' "var1" : "' . $cols[1] . "\",\n";
$json .= ' "var2" : "' . $cols[2] . "\",\n";
$json .= ' "var3" : "' . $cols[3] . "\",\n";
$json .= ' "var4" : "' . $cols[4] . "\",\n";
$json .= ' "var5" : "' . $cols[5] . "\",\n";
$json .= ' "var6" : "' . $cols[6] . "\",\n";
$json .= ' "var7" : "' . $cols[7] . "\",\n";
$json .= ' "var8" : "' . $cols[8] . "\",\n";
$json .= ' "var9" : "' . $cols[9] . "\",\n";
$json .= ' "var10" : "' . $cols[10] . '"';
$json .= "\n }";
if ($i !== $len - 1) {
$json .= ',';
}
$i++;
}
$json .= "\n ]\n}";
return $json;
}
$json = csvToJSON($csv);
$json = preg_replace('/[ \n]/', '', $json);
header('Content-Type: text/plain');
header('Cache-Control: no-cache');
echo $json;
$csv
变量是由返回 CSV 内容的 cURL 请求产生的字符串。
我确信这不是最有效的 PHP 代码,因为我是一名初学者开发人员,而且我对 PHP 的了解很少。 是否有更好、更有效的方法使用 PHP 将 CSV 转换为 JSON?
提前致谢。
注意。我知道我添加了空格,然后将其删除,我这样做是为了可以选择通过删除行 $json = preg_replace(' 来返回“可读”JSON /[ \n]/', '', $json);
用于测试目的。
编辑。感谢您的回复,根据您的回复,新代码如下:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$csvarr = array_map(function ($row) {
$keys = array('var0','var1','var2','var3','var4','var5','var6','var7','var8','var9','var10');
return array_combine($keys, str_getcsv($row));
}, $rows);
$json = json_encode($csvarr);
return $json;
}
$json = csvToJson($csv);
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $json;
I need to convert a CSV file to JSON on the server using PHP. I am using this script which works:
function csvToJSON($csv) {
$rows = explode("\n", $csv);
$i = 0;
$len = count($rows);
$json = "{\n" . ' "data" : [';
foreach ($rows as $row) {
$cols = explode(',', $row);
$json .= "\n {\n";
$json .= ' "var0" : "' . $cols[0] . "\",\n";
$json .= ' "var1" : "' . $cols[1] . "\",\n";
$json .= ' "var2" : "' . $cols[2] . "\",\n";
$json .= ' "var3" : "' . $cols[3] . "\",\n";
$json .= ' "var4" : "' . $cols[4] . "\",\n";
$json .= ' "var5" : "' . $cols[5] . "\",\n";
$json .= ' "var6" : "' . $cols[6] . "\",\n";
$json .= ' "var7" : "' . $cols[7] . "\",\n";
$json .= ' "var8" : "' . $cols[8] . "\",\n";
$json .= ' "var9" : "' . $cols[9] . "\",\n";
$json .= ' "var10" : "' . $cols[10] . '"';
$json .= "\n }";
if ($i !== $len - 1) {
$json .= ',';
}
$i++;
}
$json .= "\n ]\n}";
return $json;
}
$json = csvToJSON($csv);
$json = preg_replace('/[ \n]/', '', $json);
header('Content-Type: text/plain');
header('Cache-Control: no-cache');
echo $json;
The $csv
variable is a string resulting from a cURL request which returns the CSV content.
I am sure this is not the most efficient PHP code to do it because I am a beginner developer and my knowledge of PHP is low. Is there a better, more efficient way to convert CSV to JSON using PHP?
Thanks in advance.
Note. I am aware that I am adding whitespace and then removing it, I do this so I can have the option to return "readable" JSON by removing the line $json = preg_replace('/[ \n]/', '', $json);
for testing purposes.
Edit. Thanks for your replies, based on them the new code is like this:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$csvarr = array_map(function ($row) {
$keys = array('var0','var1','var2','var3','var4','var5','var6','var7','var8','var9','var10');
return array_combine($keys, str_getcsv($row));
}, $rows);
$json = json_encode($csvarr);
return $json;
}
$json = csvToJson($csv);
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $json;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
那么,您应该使用 json_encode() 函数,而不是自己构建 JSON 输出。还有一个用于解析 CSV 的函数 str_getcsv():
但是,如果您希望 JSON 输出保存命名字段,则必须调整 $array。
Well there is the json_encode() function, which you should use rather than building up the JSON output yourself. And there is also a function str_getcsv() for parsing CSV:
You must however adapt the $array if you want the JSON output to hold named fields.
我修改了问题中的答案,以使用 CSV 的第一行作为数组键。这样做的优点是不必对函数中的键进行硬编码,使其适用于任何具有列标题和任意数量列的 CSV。
这是我的修改版本:
I modified the answer in the question to use the first line of the CSV for the array keys. This has the advantage of not having to hard-code the keys in the function allowing it to work for any CSV with column headers and any number of columns.
Here is my modified version:
这些答案都不适用于多行单元格,因为它们都假设行以“\n”结尾。内置
fgetcsv
函数了解多行单元格包含在 " 中,因此不会遇到相同的问题。下面的代码不依赖 '\n' 来查找 csv 的每一行,而是 < code>fgetcsv 逐行准备我们的输出。None of these answers work with multiline cells, because they all assume a row ends with '\n'. The builtin
fgetcsv
function understands that multiline cells are enclosed in " so it doesn't run into the same problem. The code below instead of relying on '\n' to find each row of a csv letsfgetcsv
go row by row and prep our output.一些提示...
fopen()
和包装器启用了 URL 打开,则可以使用fgetscsv()
。进行转换json_encode()
。application/json
。Some tips...
fopen()
and wrappers, you can usefgetscsv()
.json_encode()
.application/json
.您可以通过删除所有空格和 \n 来减少开销。但这是在你的笔记中。
您可以通过跳过 preg_replace 并传递一个可打开和关闭它的布尔值来提高性能。
除此之外,var[1-10] 的变量展开实际上很好,只要始终有十个变量即可。
爆炸和 foreach 方法都很好。
You could probably reduce the overhead by removing all the spaces and \n's. But that's in your note.
You could increase the performance by skipping the preg_replace and passing a boolean that would turn it on and off.
Other than that, the variable unrolling of your var[1-10] actually is good, as long as there are always ten varaibles.
The explode and the foreach approach are just fine.
我建议使用 Coseva (一个 csv 解析库)并使用内置的 toJSON() 方法。
I recommend using Coseva (a csv parsing library) and using the built in toJSON() method.