PHP将JSON文件转换为Excel表的格式不正确
我已经做了一个PHP文件,这个基于JSON的文件:
http://www.yellowpages.com.iq/ajax/get/register/Categories.php
并使用以下代码将其转换为格式为(.cvs)的excel格式表:
$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;
但问题是,是否需要数据并正确显示,尽pipe它倾向于如此格式化:
id 1类广告
ID 2类农业和食品
ID 3类空调
id 4类航空公司
ID 5铝和玻璃
而不是我试图让它看起来像我手动:
任何帮助,将不胜感激!
您可以使用fputcsv
来更改代码,这会处理双引号并将其转义。
为此,您需要将JSON作为关联数组(提供第二个参数为true
):
$data = JSON_decode($contents, true);
然后你的循环将被replace为:
// "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); }