[英]PHP converting JSON file into excel table is formatted incorrectly
$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php'); $data = JSON_decode($contents); $excel_file = fopen("file.csv", "a+"); $table = "<table border='1'>"; foreach($data as $elem) { $table .= "<tr>"; foreach($elem as $key => $prop) { $table .= "<th>$key</th>"; $table .= "<td>$prop</td>"; fwrite($excel_file, "$key,$prop\\n"); } $table .= "</tr>"; } $table .= "</table>"; echo $table;
但是问题是,尽管它倾向于像这样格式化数据,但它是否会获取数据并正确显示它:
id 1类别广告
id 2分类农业与食品
id 3类别空调
id 4类别航空公司
id 5铝和玻璃
您可以使用fputcsv
更改代码,该代码可以处理双引号并将其转义。
为此,您需要将JSON作为关联数组(提供第二个参数true
):
$data = JSON_decode($contents, true);
然后,您拥有的循环将被替换为:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.