Google Search API PHP Script
I needed a simple script to display site search results using the Google AJAX Search API. However, I’m not using any JavaScript — just pure PHP. After searching, it appears that Google discontinued their standard Google Search API a few years ago in favor of the Google AJAX Search API; the major difference is that the new API returns JSON instead of XML. Thanks to PHP5 it is easy to convert JSON to a standard array and loop as required.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<?php
function retrieveGoogleSearch($searchTerms="PHP",$searchURL="site:www.Wercshop.com") {
$googleBaseUrl = "http://ajax.googleapis.com/ajax/services/search/web";
$googleBaseQuery = "?v=1.0&q=";
$googleFullUrl = $googleBaseUrl . $googleBaseQuery . $searchURL . "%20" . $searchTerms;
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$googleFullUrl);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_REFERER,"http://www.b13ed.com/");
$returnGoogleSearch = curl_exec($curlObject);
curl_close($curlObject);
$returnGoogleSearch = json_decode($returnGoogleSearch,true);
return $returnGoogleSearch["responseData"]["results"];
}
$setSearchTerms = "JavaScript";
$setSearchURL = "site:www.MercuryState.com";
$searchResultsArray = retrieveGoogleSearch($setSearchTerms,$setSearchURL);
?>
</head>
<body>
<ol>
<? foreach($searchResultsArray as $result): ?>
<li><strong><a href="<?=$result["url"];?>"><?=$result["title"];?></a></strong> <?=$result["content"];?> <em><?=$result["visibleUrl"];?></em></li>
<? endforeach; ?>
</ol>
</body>
</html>
About this entry
You’re currently reading “Google Search API PHP Script,” an entry on Wercshop
- Published:
- 09.16.08 / 4pm
- Category:
- PHP
No comments
Jump to comment form | comments rss [?] | trackback uri [?]