2013-05-03 75 views
0

我想知道如何使用PHP來解析下面的JSON並將解析後的值輸出爲CSV格式。使用PHP解析JSON並將其輸出爲CSV

{ 
"test":{"12345":"98765","56789":"54321"}, 
"control":{"99999":"98765","88888":"98765"} 
} 

我想只提取從test陣列的按鍵(即1234556789),並且它們在CSV格式返回。有可能使用json_decode嗎?

請,如果您需要了解更多信息

+0

所有的值在一行或每個值一行?你想輸出爲網頁還是本地輸出到文件? – Roger 2013-05-03 23:19:06

+0

各值1行,請 – 585connor 2013-05-03 23:19:52

+1

雖然什麼是關於一個價值/行的CSV? – chelmertz 2013-05-03 23:25:31

回答

5
$json = json_decode($json, true); 
fputcsv(fopen('file', 'w'), array_keys($json['test'])); 
+0

json_decode返回作爲一個對象,你不能稱它爲array_keys中的數組.. – Dinesh 2013-05-03 23:28:32

+0

@Dinesh http://us1.php.net/manual/en/function。 json-decode.php - 第二個參數 – 2013-05-03 23:30:10

+0

廢話.. did not see the true .. sorry buddy .. +1 – Dinesh 2013-05-03 23:31:18

0
$s = '{ 
"test":{"12345":"98765","56789":"54321"}, 
"control":{"99999":"98765","88888":"98765"} 
}'; 


$json = json_decode($s, true); 
echo implode("\n", array_keys($json['test'])); 

那會做隨意問任何問題嗎?

+0

這工作,但沒有輸出到CSV文件。雖然謝謝! – 585connor 2013-05-03 23:32:46

+1

@ 585connor寫入文件是你可能應該閱讀的東西。 :)見http://se1.php.net/file_put_contents – chelmertz 2013-05-03 23:36:19