2012-12-18 81 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)) 

我懷疑這是最佳的方式,所以如果任何人有一個更好的解決方案隨意添加它。