簡體   English   中英

在XML文件中搜索多個元素

[英]Searching Multiple Elements In XML File

我正在使用此處找到的W3C Live Ajax搜索。 他們的代碼僅搜索一個元素,即“標題”。 我想讓它接受用戶的查詢並搜索多個元素,例如“ title”和“ url”。

<?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只會搜索一個干草堆,而您不能使用數組,那么還有另一種方法嗎? 提前致謝!

好吧,我想出了一種方法:

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

我懷疑這是否是最佳方法,因此如果有人有更好的解決方案,請隨時添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM