i.am i.am - 2 months ago 27
JSON Question

google search, json_decode gives null

$query = "Poultry meat is a major source of animal protein considering";

function fetch_google($query) {
$cleanQuery = str_replace(" ","+",$query);

$url = 'http://www.google.com/search?q='.urlencode($cleanQuery);
$data=file_get_contents($url);
$json = json_decode($data, true);

for($x=0;$x<count($json->responseData->results);$x++){

echo "<b>Result ".($x+1)."</b>";
echo "<br>URL: ";
echo $json->responseData->results[$x]->url;
echo "<br>VisibleURL: ";
echo $json->responseData->results[$x]->visibleUrl;
echo "<br>Title: ";
echo $json->responseData->results[$x]->title;
echo "<br>Content: ";
echo $json->responseData->results[$x]->content;
echo "<br><br>";
}
}

fetch_google($query);


i am try to get search result, but in return json_decode giving null values ..
tried searching for answer but failed.

var_dump($url);
gives result .. but not $json

Answer

You loaded the full google search results page. The result in $data will be the full HTML returned by the page, not a json formatted result.

You need to call the google API in order to receive a JSON that can be easily manipulate from PHP

Check the official documentation here about google search