用PHP在XML中搜索

用PHP在XML中搜索,php,ajax,search,Php,Ajax,Search,尝试将Ajax搜索功能添加到xml文件,发现以下示例: <?php $xmlDoc=new DOMDocument(); $xmlDoc->load("my_xml_file.xml"); $x=$xmlDoc->getElementsByTagName('links'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of

尝试将Ajax搜索功能添加到xml文件,发现以下示例:

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

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

//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++) {
    $y=$x->item($i)->getElementsByTagName('title');
    $z=$x->item($i)->getElementsByTagName('url');
    if ($y->item(0)->nodeType==1) {
      //find a link matching the search text
      if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
        if ($hint=="") {
          $hint="<a href='" . 
          $z->item(0)->childNodes->item(0)->nodeValue . 
          "' target='_blank'>" . 
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        } else {
          $hint=$hint . "<br /><a href='" . 
          $z->item(0)->childNodes->item(0)->nodeValue . 
          "' target='_blank'>" . 
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

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

//output the response
echo $response;
?>
但如何改变呢

 $y=$x->item($i)->getElementsByTagName('title');
拥有
$y=$x->item($i)->名称
$z=$x->item($i)->数据
没有CDATA的内容

谢谢你的帮助

将此添加到循环中:

 $attr = $a->item($i)->getAttribute('name');
if($attr==""){
continue;
}
//take care of the $attr

echo $attr;

你能给我们发一个你试图搜索的xml文件的示例吗?就我个人而言,我会放弃DOM函数,因为我总是觉得它太冗长,而使用它。手册中有一些很好的例子介绍了如何使用它,请记住print\u r和var\u dump不能很好地使用它。在SimpleXML中获取字符串内容或CDATA的工作方式相同:
$content=(string)$element
我发布了一个解决您问题的解决方案,但是,我同意@IMSoP
 $y=$x->item($i)->getElementsByTagName('title');
 $attr = $a->item($i)->getAttribute('name');
if($attr==""){
continue;
}
//take care of the $attr

echo $attr;