I'm trying to build a metasearch engine, and have the following code which generates JSON results.
<?php
$search = $_GET['results'];
if(isset($_GET['results']) && $_GET['results'] != "")
{
echo "<br />Your Search Result Array:<br /><br />";
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".str_replace(' ', '%20', $_GET['results']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
print_r($json);
This gives me JSON unsorted results, without an order or hyperlinks. I am trying to parse to results using PHP. When I type "hello" into the search engine it gives me
stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( [0] =>stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.hellomagazine.com/ [url] => http://www.hellomagazine.com/ [visibleUrl] => www.hellomagazine.com [cacheUrl] => http://www.google.com/search?q=cache:QzMhUCC4zBoJ:www.hellomagazine.com [title] => HELLO! Online: celebrity & royal news, magazine, babies,
as the first 4 lines. I tried
foreach($results['responsedata']['results']['GsearchResultsClass'] as $result)
{
echo $result['title'].'<br/>';
}
but it leaves me with tonnes of errors on the foreach line.
Any advice greatly appreciated, i am not familiar with JSON so any help is welcome on how to parse the results.
your using the default return type of json_encode
, which returns a stdClass object. If you want to consume it as a associative array then pass this following parameter to json_decode.
$json = json_decode($json, true);