Code for retrieving Google AJAX Search API data using PHP

Source: Internet
Author: User

Http://code.google.com/apis/ajaxsearch/documentation/#fonje
Copy codeThe Code is as follows:
// This example request has des an optional API key which you will need
// Remove or replace with your own key.
// Read more about why it's useful to have an API key.
// The request also provided des the userip parameter which provides the end
// User's IP address. Doing so will help distinguish this legitimate
// Server-side traffic from traffic which doesn' t come from an end-user.
$ Url = "http://ajax.googleapis.com/ajax/services/search/web? V = 1.0 &"
. "Q = Paris % 20 Hilton & key = INSERT-YOUR-KEY & userip = USERS-IP-ADDRESS ";

// 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,/* Enter the URL of your site here */);
$ Body = curl_exec ($ ch );
Curl_close ($ ch );

// Now, process the JSON string
$ Json = json_decode ($ body );
// Now have some fun with the results...

Api key application address:
Http://code.google.com/apis/ajaxsearch/signup.html

Therefore, we can write a function like this.
Copy codeThe Code is as follows:
Function google_search_api ($ args, $ referer = 'HTTP: // www.jb51.net/', $ endpoint = 'web '){
$ Url = "http://ajax.googleapis.com/ajax/services/search/". $ endpoint;
If (! Array_key_exists ('V', $ args ))
$ Args ['V'] = '1. 0 ';
$ Url. = '? '. Http_build_query ($ args ,'','&');
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_REFERER, $ referer );
$ Body = curl_exec ($ ch );
Curl_close ($ ch );
Return json_decode ($ body );
}

// Example
$ Rez = google_search_api (array (
'Q' => '21andy. com', // query the content
'Key' => 'api key' you applied ',
'Userip' => 'your IP address ',
));
Header ('content-type: text/html; charset = UTF-8 ;');
Echo '<xmp> ';
Print_r ($ rez );
Echo '</xmp> ';

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.