2013-03-20 96 views
0

我需要爲SocialMention.com查詢「Colorado Springs」和「District 11」,並將數據提取回CSV文件。我是一位老程序員,但是對PHP和JSON是新手。這裏是簡單的PHP代碼:如何在PHP中將JSON解析爲CSV用於社交API

<?php 
$curl = curl_init('http://api.socialmention.com/search?q=%22colorado+springs%22+%22district+11%22&f=json&src[]=twitter&sentiment=true&meta=info'); 
$result = curl_exec($curl); 
echo $result; 
?> 

如何解析$ result並將其存儲在CSV文件中?我一直在研究這個爲期6天,並嘗試過每一個我找不到的例子。在下面的例子中,我不斷收到「foreach中的無效參數」錯誤。

回答

0

你的問題很廣泛,因爲你沒有真正說出你想如何解析$result,但你甚至沒有得到$result,因爲curl_exec實際上會打印出它的內容。相反,你可以設置curl_setopt($curl, CURLOPT_RETURNTRANSFER, true),或者你可能只用$result = file_get_contents($url);

無論如何,你可以從JSON通過$data = json_decode($result, true)結果變成可用的PHP數據結構。第二個參數強制關聯數組,這可能更適合您的目的。

然後,你可以寫CSV文件:

$fh = fopen('csvfile', 'w'); 
foreach ($result['items'] as $items) { 
    fputcsv($fh, $items); 
} 
0

ü可以參考兩個環節太

1. Parsing JSON file with PHP

2. php writing to csv from an array

$json_a=json_decode($string,true); //decodes json 

//writes to csv 
$fp = fopen('file.csv', 'w'); 

    for ($i = 0; $i < count($json_a); $i++) { 
     $fields = //json object feids here 
     fputcsv($fp, $fields); 
    } 

    fclose($fp);