【发布时间】:2017-03-14 11:49:38
【问题描述】:
您好,我在将 json 转换为 csv 时遇到了小问题。 这是我的代码:
$jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}';
//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);
//Give our CSV file a name.
$csvFileName = 'file.csv';
//Open file pointer.
$fp = fopen($csvFileName, 'w');
//Loop through the associative array.
foreach($jsonDecoded as $row){
//Write the row to the CSV file.
fputcsv($fp, $row);
}
//Finally, close the file pointer.
fclose($fp);
?>
我尝试过使用像 [{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}] 这样的另一种 json 格式,它的工作非常完美。
如何修改我的代码以正确保存为 csv 格式。
有人可以帮我吗?
【问题讨论】:
-
了解你的数据结构,即
$jsonDecoded数组,然后你就会发现你做错了什么