这个类可以在网上搜索,使用了Bing搜索API。它可以发送HTTP请求到Bing搜索API的Web服务器执行搜索Web内容使用以前获得的API密钥。 类可以搜索网页,图片,视频,新闻和相关的关键字。
<?
/**
* 使用bing api搜索网站的PHP封装类
*
* @param
* @author 编程之家 jb51.cc jb51.cc
**/
class BingAPI{
var $accountKey = '';
var $ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
var $WebSearchURL;
var $searchText;
var $searchType;
var $request_data;
var $AutoGet = true;
var $ReturnType = 'JSON'; //Options: JSON,ARRAY
var $ResultsLimit = 10;
function __construct(){
}
function setQuery_Type($query,$type){
$this->searchText = $query;
switch($type){
case 'Web':$this->searchType = 'Web';break;
case 'Image':$this->searchType = 'Image';break;
case 'News':$this->searchType = 'News';break;
case 'Video':$this->searchType = 'Video';break;
case 'Related':$this->searchType = 'RelatedSearch';break;
}
$this->createURL();
}
function createURL(){
$this->WebSearchURL = $this->ServiceRootURL . $this->searchType .'?$format=json&$top='.$this->ResultsLimit.'&Query=';
$this->context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,'header' => "Authorization: Basic " . base64_encode($this->accountKey . ":" . $this->accountKey)
)
));
$this->request = $this->WebSearchURL . urlencode( '\'' . $this->searchText . '\'');
if($this->AutoGet){
$this->get();
}
}
function get(){
$response = file_get_contents($this->request,$this->context);
$this->request_data = json_decode($response);
}
function decoded_data(){
$r_array = array();
switch($this->searchType){
case 'Web':
$obj = $this->request_data->d->results;
$ic = count($obj);
for($i=0;$i<$ic;$i++){
$r_array[$i] = array('Title'=>$obj[$i]->Title,'Description'=>$obj[$i]->Description,'Url'=>$obj[$i]->Url);
}
break;
case 'Image':
$obj = $this->request_data->d->results;
$ic = count($obj);
for($i=0;$i<$ic;$i++){
$r_array[$i] = array('Title'=>$obj[$i]->Title,'MediaURL'=>$obj[$i]->MediaUrl,'Width'=>$obj[$i]->Width,'Height'=>$obj[$i]->Height,'ContentType'=>$obj[$i]->ContentType,'Thumbnail'=>$obj[$i]->Thumbnail->MediaUrl);
}
break;
case 'News':
$obj = $this->request_data->d->results;
$ic = count($obj);
for($i=0;$i<$ic;$i++){
$r_array[$i] = array('Title'=>$obj[$i]->Title,'Url'=>$obj[$i]->Url,'Source'=>$obj[$i]->Source,'Date'=>$obj[$i]->Date);
}
break;
case 'Video':
$obj = $this->request_data->d->results;
$ic = count($obj);
for($i=0;$i<$ic;$i++){
$r_array[$i] = array('Title'=>$obj[$i]->Title,'MediaUrl'=>$obj[$i]->MediaUrl,'DisplayUrl'=>$obj[$i]->DisplayUrl,'Runtime'=>$obj[$i]->Runtime,'Thumbnail'=>$obj[$i]->Thumbnail->MediaUrl);
}
break;
case 'RelatedSearch':
$obj = $this->request_data->d->results;
$ic = count($obj);
for($i=0;$i<$ic;$i++){
$r_array[$i] = array('Keyword'=>$obj[$i]->Title);
}
break;
}
switch($this->ReturnType){
case 'JSON':return json_encode($r_array);
case 'ARRAY':return $r_array;
}
}
}
/*** 来自编程之家 jb51.cc(jb51.cc) ***/
原文链接:https://www.f2er.com/php/528741.html