php如何实现调用搜索引擎接口;这里有两个方案;
一:PHP自带的curl,当然首先要开启curl,这里不多赘述。
代码如下:
$data = array(
\'q\'=>$solrsel,
\'wt\'=>\'json\',
\'indent\'=>\'true\'
);
$ch = curl_init(); //实例化
curl_setopt($ch, CURLOPT_HTTPHEADER, 0);//设置header编码格式
curl_setopt($ch, CURLOPT_URL, "http://115.28.140.107:8080/solr/medidoctor/select");//url地址
curl_setopt($ch, CURLOPT_POST, true);//是否post请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post请求传递的数据,请求接口地址需要带的参数
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//返回获取的输出文本流
$response = curl_exec($ch);//获取返回的数据,这里返回的是json数据可根据具体情况进行解析使用
curl_close($ch);//关闭
二:使用solr-php-client
首先:下载包我下载的是这个https://solr-php-client.googlecode.com/files/SolrPhpClient.r22.2009-11-09.zip
其次:将其解压,拷贝出来apache文件夹到你需求目录下。
然后以下代码进行使用:
header(\'Content-Type: text/html; charset=utf-8\');//编码格式
$limit = 10;//取几条数据
$query = isset($_REQUEST[\'q\']) ? $_REQUEST[\'q\'] : false;//查询的关键字
$results = false;
if ($query)
{
// The Apache Solr Client library should be on the include path
// which is usually most easily accomplished by placing in the
// same directory as this script ( . or current directory is a default
// php include path entry in the php.ini)
require_once(\'apache/solr/Service.php\');
// create a new solr service instance - host, port, and webapp
// path (all defaults in this example)
$solr = new Apache_Solr_Service(\'115.28.140.107\', 8080, \'/solr/medidoctor/\');
// if magic quotes is enabled then stripslashes will be needed
if (get_magic_quotes_gpc() == 1)
{
$query = stripslashes($query);
}
// in production code you\'ll always want to use a try /catch for any
// possible exceptions emitted by searching (i.e. connection
// problems or a query parsing error)
try
{
//以下为返回的解析方法,这里我将其解析存放到数组中然后jsonp的形式返回给html
$re=array();
$i=0;
$results = $solr->search($query, 0, $limit);
foreach ($results->response->docs as $doc)
{
$arr=array();
foreach ($doc as $field => $value)
{
$arr[htmlspecialchars($field, ENT_NOQUOTES, \'utf-8\')]=htmlspecialchars($value, ENT_NOQUOTES, \'utf-8\');
}
$re[$i]=$arr;
$i=$i+1;
}
$return=array(
"doclist"=>$re
);
echo $_GET[\'callback\'].\'(\'.json_encode($return).\')\';
exit();
}
catch (Exception $e)
{
// in production you\'d probably log or email this error to an admin
// and then show a special message to the user but for this example
// we\'re going to show the full exception
die("<html><head><title>SEARCH EXCEPTION</title><body><pre>{$e->__toString()}</pre></body></html>");
}
}