doukanwa6872 2012-09-11 08:19
浏览 31
已采纳

如何使用PHP在XML中搜索某些名称

I want to be able to go trough the each of the nodes in XML and when I find a certain username I want to read all the data from that node.

For example:

<Users>
   <User>
      <Username>admin</Username>
      <Server>10.x.x.x</Server>
   </User>
   <User>
      <Username>test</Username>
      <Server>11.x.x.x</Server>
   </User>
</Users>

I need to be able to find Username=admin and then get the Server from the same node. I will be using a PHP and you can make example with saving in any two variables.

  • 写回答

3条回答 默认 最新

  • du1068 2012-09-11 08:50
    关注

    Using Xpath and DomDocument , something like this should do the trick :

    $doc = new DOMDocument;
    $doc->loadXML($xml); // Your xml string
    $xpath = new DOMXpath($doc);
    
    $query = '//Users/User/Username[. = "admin"]'; // Looking for user admin
    $entries = $xpath->query($query);
    
    foreach ($entries as $entry) {
        //Getting the "server" node value for "admin" user
        echo $entry->nextSibling->nextSibling->nodeValue; // Display 10.x.x.x
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题