0

I need to query SocialMention.com for "Colorado Springs" and "District 11" and pull the data back into a CSV file. I'm an old programmer but new to PHP and JSON. Here's the simple php code:

<?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; 
?> 

How do I parse $result and store it in a CSV file? I've been researching this for 6 days and have tried every example I can find with no luck. In the examples below I keep getting an "Invalid argument in foreach" error.

2 Answers2

0

Your question is broad since you don't really say how you want to parse $result, but you're not even getting $result because curl_exec will actually print out its contents. Instead you can set curl_setopt($curl, CURLOPT_RETURNTRANSFER, true), or you can probably just use$result = file_get_contents($url);

Anyway, you can change the result from JSON to usable PHP data structure via $data = json_decode($result, true). The second argument forces associative arrays, which are probably better for your purposes.

Then you can write to the CSV file:

$fh = fopen('csvfile', 'w');
foreach ($result['items'] as $items) {
    fputcsv($fh, $items);
}
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

u can refer the two links too

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);
Community
  • 1
  • 1
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46