使用PHP检索XML节点的子集 [英] Retrieving a subset of XML nodes with PHP

查看:129
本文介绍了使用PHP检索XML节点的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP,如何从XML文档中获取整个节点子集?我可以检索到以下内容:

Using PHP, how do I get an entire subset of nodes from an XML document? I can retrieve something like:

<?xml version="1.0" encoding="utf-8"?>
<people>
  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>
</people>

但是,如果我只想返回这样的子节点怎么办?

But what if I only want to return the child nodes of like this?

  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>

我正在尝试获取XML的子集并直接传递它,而不是像simplexml这样的对象会给我.我基本上是想让PHP来执行.NET OuterXml的工作...按原样返回XML的上述子集...不解释,转换或创建新的XML文件或其他任何东西...只需就地提取这些节点并传递给他们.我是否必须获取XML文件,解析出我需要的内容,然后将其重建为新的XML文件?如果是这样,那么我需要摆脱<?xml version="1.0" encoding="utf-8"?>位...嗯.

I'm trying to get a subset of XML and pass that directly, not an object like simplexml would give me. I am basically trying to get PHP to do what .NET's OuterXml does... return literally the above subset of XML as is... no interpreting or converting or creating a new XML file or anything... just extract those nodes in situ and pass them on. Am I going to have to get the XML file, parse out what I need and then rebuild it as a new XML file? If so then I need to get rid of the <?xml version="1.0" encoding="utf-8"?> bit... ugh.

推荐答案

答案是使用 XPath .

$people = simplexml_load_string(
    '<?xml version="1.0" encoding="utf-8"?>
    <people>
      <certain>
        <name>Jane Doe</name>
        <age>21</age>
      </certain>
      <certain>
        <name>John Smith</name>
        <age>34</age>
      </certain>
    </people>'
);

// get all <certain/> nodes
$people->xpath('//certain');

// get all <certain/> nodes whose <name/> is "John Smith"
print_r($people->xpath('//certain[name = "John Smith"]'));

// get all <certain/> nodes whose <age/> child's value is greater than 21
print_r($people->xpath('//certain[age > 21]'));


参加2

显然,您想将某些节点从一个文档复制到另一个文档中吗? SimpleXML不支持该功能. DOM 具有用于此目的的方法,但使用起来有点令人讨厌.您正在使用哪一个?这是我使用的方法: SimpleDOM .实际上,它确实是SimpleXML,并添加了DOM的方法.


Take 2

So apparently you want to copy some nodes from a document into another document? SimpleXML doesn't support that. DOM has methods for that but they're kind of annoying to use. Which one are you using? Here's what I use: SimpleDOM. In fact, it's really SimpleXML augmented with DOM's methods.

include 'SimpleDOM.php';
$results = simpledom_load_string('<results/>');

foreach ($people->xpath('//certain') as $certain)
{
    $results->appendChild($certain);
}

该例程通过XPath找到所有<certain/>节点,然后将它们附加到新文档中.

That routine finds all <certain/> node via XPath, then appends them to the new document.

这篇关于使用PHP检索XML节点的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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