Pull data from Google Search API and decode JSON string using PHP
June 11th, 2008PHP has a built-in function that can decode a JSON string and turn into an object or an object tree and is called PHP-JSON. This is very helpful for when you need to integrate or mashup with other application such as the google APIs. Here is a quick simple example:
<?php
$json_str = ‘{ “name” : “chris”}’;
$obj = json_decode($json_str);
echo $obj->name;
echo “\n”;
The above will return:
chris
Here is a more complex example using the actual Google Searh API:
<?php
$url = “http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton”;
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, “http://www.chrisdevbox.com/”);
$body = curl_exec($ch);
//echo $body;
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results…
print_r($json);
Pretty cool huh? I think the coolest part is the fact that you can pretty much pull anything from google using this… including video, news, blogs, etc… I’ll be writing another article on that. Stay tuned.
BTW, PHP-JSON comes built in with PHP 5.2, for earlier version you’ll have to download, compile and install.
Simple steps
- wget http://aurore.net/projects/php-json/php-json-ext-1.2.1.tar.bz2
- tar xvf php-json-ext-1.2.1.tar.bz2
- cd php-json-ext-1.2.1
- phpize
- ./configure
- make
- make install
- vi /etc/php.ini
- Add the following:
- extension=json.so

June 13th, 2008 at 1:17 am
[...] helpful for when you need to integrate or mashup with other application such as the google APIs.http://www.chrisdevbox.com/blog/2008/06/11/pull-data-from-google-search-api-and-decode-json-string-u…MTV Ultimate Mash UpsMusic…MTV Ultimate Mash Ups edit remix green day oasis nirvana7 min [...]
August 16th, 2008 at 8:01 pm
Your blog is interesting!
Keep up the good work!
October 14th, 2008 at 8:43 am
But how to do site search with this code. what are the parameters to send with url .
i searched but not successful.
And json_decode() -function is avialable only for php 5.2.0.
below this version we have to include JSON.php.
Is it possible..