2012-12-18 60 views
0

我正在使用W3C Live Ajax搜索找到here。他们的代码只搜索一个元素,即“标题”。我想让用户查询并搜索多个元素,例如“标题”和“网址”。在XML文件中搜索多个元素

<?php 
$xmlDoc=new DOMDocument(); 
$xmlDoc->load("live.xml"); 

$x=$xmlDoc->getElementsByTagName('link'); 

//get the q parameter from URL 
$q=$_GET["q"]; 

//lookup all links from the xml file if length of q>0 
if (strlen($q)>0) 
{ 
$hint=""; 
for($i=0; $i<($x->length); $i++) 
    { 
    $d=$x->item($i)->getElementsByTagName('title'); 
    $z=$x->item($i)->getElementsByTagName('url'); 
    if ($d->item(0)->nodeType==1) 
    { 
    //find a link matching the search text 
    if (stristr($d->item(0)->childNodes->item(0)->nodeValue,$q) !=false) 
     { 
     if ($hint=="") 
     { 
     $hint= 
     $z->item(0)->childNodes->item(0)->nodeValue . "<br />" . 
     $d->item(0)->childNodes->item(0)->nodeValue; 
     } 
     else 
     { 
     $hint=$hint . "<br /><br />" . 
     $z->item(0)->childNodes->item(0)->nodeValue . "<br />" . 
     $d->item(0)->childNodes->item(0)->nodeValue; 
     } 
     } 
    } 
    } 
} 

// Set output to "no suggestion" if no hint were found 
// or to the correct values 
if ($hint=="") 
    { 
    $response="no suggestion"; 
    } 
else 
    { 
    $response=$hint; 
    } 

//output the response 
echo $response; 

?> 

有人能给我一个如何使它工作的例子吗?根据我的理解,stristr只会搜索一个干草堆,而不能使用数组,所以还有其他方法吗?提前致谢!

回答

0

嗯,我想出了一个办法:

if ((stristr($d->item(0)->childNodes->item(0)->nodeValue,$q) !=false) || 
    (stristr($z->item(0)->childNodes->item(0)->nodeValue,$q) !=false)) 

我怀疑这是最佳的方式,所以如果任何人有一个更好的解决方案随意添加它。