【问题标题】:Searching Multiple Elements In XML File在 XML 文件中搜索多个元素
【发布时间】:2012-12-18 21:15:22
【问题描述】:

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

<?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 只会搜索一个干草堆,而您不能使用数组,那么还有另一种方法吗?提前致谢!

【问题讨论】:

    标签: php xml xml-parsing domdocument


    【解决方案1】:

    嗯,我想出了一个办法:

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

    我怀疑这是最佳方式,所以如果有人有更好的解决方案,请随时添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 2012-05-17
      • 1970-01-01
      • 2014-02-15
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多