Processing data in a PHP JSON object

Trending data from the Twitter Search API in JSON.

File capture using:

$jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); 

How to work with the data of this object. How is the array? Just really need to extract data from the [name] values.

The JSON object contains:

 stdClass Object ( [trends] => Array ( [0] => stdClass Object ( [name] => Vote [url] => http://search.twitter.com/search?q=Vote ) [1] => stdClass Object ( [name] => Halloween [url] => http://search.twitter.com/search?q=Halloween ) [2] => stdClass Object ( [name] => Starbucks [url] => http://search.twitter.com/search?q=Starbucks ) [3] => stdClass Object ( [name] => #flylady [url] => http://search.twitter.com/search?q=%23flylady ) [4] => stdClass Object ( [name] => #votereport [url] => http://search.twitter.com/search?q=%23votereport ) [5] => stdClass Object ( [name] => Election Day [url] => http://search.twitter.com/search?q=%22Election+Day%22 ) [6] => stdClass Object ( [name] => #PubCon [url] => http://search.twitter.com/search?q=%23PubCon ) [7] => stdClass Object ( [name] => #defrag08 [url] => http://search.twitter.com/search?q=%23defrag08 ) [8] => stdClass Object ( [name] => Melbourne Cup [url] => http://search.twitter.com/search?q=%22Melbourne+Cup%22 ) [9] => stdClass Object ( [name] => Cheney [url] => http://search.twitter.com/search?q=Cheney ) ) [as_of] => Mon, 03 Nov 2008 21:49:36 +0000 ) 
+84
json php
Nov 04 '08 at 20:50
source share
4 answers

Do you mean something like this?

 <?php $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); foreach ( $json_output->trends as $trend ) { echo "{$trend->name}\n"; } 
+147
Nov 04 '08 at 20:59
source share

If you use json_decode($string, true) , you will not get any objects, but all as an associative or numerical index array. The path is easier to handle, since the stdObject provided by PHP is nothing more than a dumb container with public properties that cannot be extended with your own function.

 $array = json_decode($string, true); echo $array['trends'][0]['name']; 
+35
Nov 03 '10 at
source share

Just use it as if it were an object that you defined. i.e.

 $trends = $json_output->trends; 
+8
Nov 04 '08 at 21:03
source share

A clean way would be:

 $jsonurl = 'http://search.twitter.com/trends.json'; $json = file_get_contents($jsonurl, 0, null, null); $json_output = json_decode($json, true); $trends = $json_output['trends']; foreach ($trends as $trend) { your_func($trend['name']); } 
-2
Jul 31 '14 at 12:46
source share



All Articles