如何在PHP中显示sphinx搜索结果

时间:2012-08-03 10:58:08

标签: php sphinx

如何通过PHP显示sphinx搜索结果 我已经安装了sphinx并进行了配置,但我无法通过PHP

获得结果

2 个答案:

答案 0 :(得分:3)

检查Sphinx图书馆:Sphinx Documentation

答案 1 :(得分:0)

以下代码用于从Sphinx搜索结果中获取完整内容 现在我们需要在$ SQL行中提供Id

<?php
echo "Welcome To Sphinx Search Site </br>";
$q = "html";
$sphx = sphinx_search("html", 0, 20);
$sphx['122'];


$ids = 122;

$sql =  "SELECT post_title , post_content FROM wp_posts WHERE  ID = '122'";
db();

if(  !($r = mysql_query($sql)))
    die("[MYSQL]".mysql_error() . mysql_errno() );

$max = $sphx['total'];
$num_rows = $sphx['docs'];

echo "<b>Displaying {$num_rows} results of {$max}</b><br /><br />";

while($row = mysql_fetch_assoc($r) ) {
    echo "{$row['post_title']} <br />{$row['post_content']}<br /><hr />";    
    }
mysql_free_result($r);

/*
 * SPHINX Search
 */

/*
 * Search sites by Keywords using sphinx; with an option to search sites tags only
 * @param string $q te keyword
 * @param int $i id of the first result to return
 * @param int $max max results to return
 * @param bollen $url set to true to return matches from the 'url' column only
 *
 * @return string $ids comma seperated list of ids
 */
function sphinx_search($q, $i, $limit, $post_type=true){
        require_once 'sphinxapi.php';

        $ids = '33500';

        $cl = new SphinxClient();
        $cl->SetServer( "192.168.0.89" , 9667);
        $cl->SetMatchMode( SPH_MATCH_EXTENDED  );
        $cl->SetSortMode ( SPH_SORT_RELEVANCE );
        $cl->SetFieldWeights(array('post_title' => 300));
        $cl->SetLimits( $i , $limit);
        $q = $cl->EscapeString( $q);

        //search url only
        $q = $post_type ? "@post_type {$q}" : $q;

        $result = $cl->Query( $q, 'sites sitesDelta' );

        if ( $result === false )
                error_log( '[SPHINX]Query failed: ' . $cl->GetLastError() );
        elseif ( $cl->GetLastWarning() )
                error_log( '[SPHINX]WARNING: ' .  $cl->GetLastWarning() );

        if ( !empty($result["matches"]) ){
            foreach ( $result["matches"] as $doc => $docinfo )
                 $ids .= "$doc,";
            $ids = substr( $ids, 0, -1 );
       }else
           return false;

       return  array( 'ids' => $ids, 'total' => $result['total'], 'docs' => count($result["matches"])  );

}

/*
 * Connect to MySQL
 */
function db(){

    if( !empty($GLOBALS['db']) ) return true;

    if( !$GLOBALS['db'] = mysql_connect('localhost', 'root', '' ) ) {
        die("[MYSQL]".mysql_error() . mysql_errno() );
    }
    elseif(!mysql_select_db('sphinxiirmulti')) {
        die("[MYSQL]".mysql_error() . mysql_errno() );
    }    

}
?>