weixin_33693070 2018-05-16 12:27 采纳率: 0%
浏览 37

使用PHP搜索XML

trying to add a Ajax search function to a xml file, and found this exemple :

    <?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;
?>

This works perfect but the xml I have to search is a bit different and I don't know how to setup the function according to my needs. This is how is formatted my xml :

<data name="my_name"><![CDATA[Data content]]></data>

I changed

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

But how to change

 $y=$x->item($i)->getElementsByTagName('title');

to have $y=$x->item($i)-> name; and $z=$x->item($i)->Data content without CDATA ?;

Thanx a lot for your help !!!

  • 写回答

1条回答 默认 最新

  • weixin_33735676 2018-05-16 12:42
    关注

    add this in your loop:

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭