PHP中使用Sphinx

来源:互联网 发布:js给input text赋值 编辑:程序博客网 时间:2024/06/05 01:08

1.首先,我们必须安装好Sphinx并在后台运行,安装过程请参考文档 http://blog.csdn.net/huang2017/article/details/69665057

2.PHP中调用Sphinx有两种方式

方式一:使用Sphinx官方提供的api文档,引入即可include 'sphinxapi.php'; 

方式二:

(1)在这里 https://pecl.php.net/package/sphinx/1.3.2/windows 下载Sphinx模块(根据自身环境选择相应版本,可以通过phpinfo进行查看,如下图所示)


(2)下载后解压,并将解压得到的php_sphinx.dll文件放到php的ext目录下

(3)修改php.ini文件(根据上面phpinfo中的Loaded Configuration File一栏找的php.ini的位置),添加一行extension=php_sphinx.dll

(4)再次查看phpinfo,出现sphinx扩展(如下图),表示安装成功,可以使用了

3.使用,代码如下

<?php
$keyword = $_POST['keyword'];
//$keyword = '航母';
$sphinx = new SphinxClient();
$sphinx->SetServer('localhost',9312);
$sphinx->setMatchMode(SPH_MATCH_ANY);//匹配模式 SPH_MATCH_ALL:完全匹配
$result = $sphinx->query($keyword,'*');//*表示在所有索引里面进行搜索
$ids = implode(',',array_keys($result['matches']));

$conn = mysqli_connect('localhost','root','');
mysqli_query($conn,'set names utf8');
mysqli_select_db($conn,'blog');

$sql = "select * from blog_articles where id in (".$ids.")";
$rst = mysqli_query($conn,$sql);
//给匹配关键字添加样式
$opts = array(
'before_match'=>'<font style="font-weight:bold;color:#f00;">',
'after_match'=>'</font>'
);
echo '<pre>';
while($row = mysqli_fetch_assoc($rst)){
$row2 = $sphinx->buildExcerpts($row,'test1',$keyword,$opts);//test1 配置文件中的主数据源索引
print_r($row2);
}
echo '</pre>';
?>

1 0
原创粉丝点击