用PHP获取Google AJAX Search API 数据的代码

2015-01-24信息快讯网

用PHP获取Google AJAX Search API 数据的代码

http://code.google.com/apis/ajaxsearch/documentation/#fonje

 
// This example request includes an optional API key which you will need to 
// remove or replace with your own key. 
// Read more about why it's useful to have an API key. 
// The request also includes 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%20Hilton&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 申请地址:
http://code.google.com/apis/ajaxsearch/signup.html

由此,我们可以写个函数像这样
 
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); 
} 

// 使用示例 
$rez = google_search_api(array( 
'q' => '21andy.com', // 查询内容 
'key' => '你申请到的API KEY', 
'userip' => '你的IP地址', 
)); 
header('Content-type: text/html; charset=utf-8;'); 
echo '<xmp>'; 
print_r($rez); 
echo '</xmp>'; 

关于php连接mssql:pdo odbc sql server
从手册去理解分析PHP session机制
php中用foreach来操作数组的代码
php自定义函数call_user_func和call_user_func_array详解
PHP setcookie设置Cookie用法(及设置无效的问题)
php array_push()数组函数:将一个或多个单元压入数组的末尾(入栈)
php array_pop()数组函数将数组最后一个单元弹出(出栈)
php array_map()数组函数使用说明
php array_walk() 数组函数
php array_intersect比array_diff快(附详细的使用说明)
php header Content-Type类型小结
Can't create/write to file 'C:\WINDOWS\TEMP\...MYSQL报错解决方法
php设计模式 Chain Of Responsibility (职责链模式)
php判断输入不超过mysql的varchar字段的长度范围
php的memcached客户端memcached
PHP模块 Memcached功能多于Memcache
php错误提示failed to open stream: HTTP request failed!的完美解决方法
php中处理mysql_fetch_assoc返回来的数组 不用foreach----echo
PHP 页面编码声明方法详解(header或meta)
PHP开启gzip页面压缩实例代码
php checkdate、getdate等日期时间函数操作详解
PHP Memcached + APC + 文件缓存封装实现代码
php 修改zen-cart下单和付款流程以防止漏单
PHP用mysql数据库存储session的代码
PHP set_time_limit(0)长连接的实现分析
PHP clearstatcache()函数详解
关于PHP5 Session生命周期介绍
基于pear auth实现登录验证
php 用checkbox一次性删除多条记录的方法
Search File Contents PHP 搜索目录文本内容的代码
php htmlspecialchars加强版
php foreach 使用&(与运算符)引用赋值要注意的问题
php addslashes和mysql_real_escape_string
PHP编程过程中需要了解的this,self,parent的区别
©2014-2024 dbsqp.com