在php中按属性选择xml节点 [英] Select xml node by attribute in php

查看:64
本文介绍了在php中按属性选择xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不遍历每个子对象和每个属性/值的情况下,通过了解属性值来查找节点值?

How do I find the node value by knowing the attribute value without traversing through every child and every attribute/value ?

$dom = new DOMDocument;
$dom->load('test.xml');

$rows = $dom->getElementsByTagName('row');

foreach ($rows as $row) {

$header = VALUE OF <field name="header">
$text = VALUE OF <field name="text">

}

XML:

<resultset>
  <row>
    <field name="item">2424</field>
    <field name="header">blah blah 1</field>
    <field name="text" xsi:nil="true" />
    ...
    </row>

  <row>
    <field name="item">5321</field>
    <field name="header">blah blah 2</field>
    <field name="text">some text</field>
    ...
  </row>
</resultset>

推荐答案

最简单的方法是使用 DOMXPath::query docs

The simplest thing to do is use DOMXPath::querydocs

以下代码查找<row>节点内具有名称属性等于"header"的所有<field>节点:

The following code finds all the <field> nodes within <row> nodes that have a name attribute equal to "header":

$dom = new DOMDocument;
$dom->loadXML($str); // where $str is a string containing your sample xml
$xpath = new DOMXPath($dom);
$query = "//row/field[@name='header']";

$elements = $xpath->query($query);

foreach ($elements as $field) {
  echo $field->nodeValue, PHP_EOL;
}

使用您提供的示例xml,以上输出:

Using the sample xml you provide, the above outputs:

blah blah 1
blah blah 2

这篇关于在php中按属性选择xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆