如何遍历 PHP 中的 DOM 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/191923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I iterate through DOM elements in PHP?
提问by Esa
I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via
我有一个 XML 文件加载到 DOM 文档中,我希望遍历所有“foo”标签,从它下面的每个标签中获取值。我知道我可以通过
$element = $dom->getElementsByTagName('foo')->item(0);
foreach($element->childNodes as $node){
$data[$node->nodeName] = $node->nodeValue;
}
However, what I'm trying to do, is from an XML like,
但是,我想要做的是来自 XML 之类的,
<stuff>
<foo>
<bar></bar>
<value/>
<pub></pub>
</foo>
<foo>
<bar></bar>
<pub></pub>
</foo>
<foo>
<bar></bar>
<pub></pub>
</foo>
</stuff>
iterate over every footag, and get specific baror pub, and get values from there. Now, how do I iterate over fooso that I can still access specific child nodes by name?
迭代每个foo标签,并获取特定的bar或pub,并从那里获取值。现在,我如何遍历foo以便我仍然可以按名称访问特定的子节点?
回答by roryf
Not tested, but what about:
未测试,但关于:
$elements = $dom->getElementsByTagName('foo');
$data = array();
foreach($elements as $node){
foreach($node->childNodes as $child) {
$data[] = array($child->nodeName => $child->nodeValue);
}
}
回答by Robert Rossney
It's generally much better to use XPath to query a document than it is to write code that depends on knowledge of the document's structure. There are two reasons. First, there's a lot less code to test and debug. Second, if the document's structure changes it's a lot easier to change an XPath query than it is to change a bunch of code.
使用 XPath 查询文档通常比编写依赖于文档结构知识的代码要好得多。有两个原因。首先,要测试和调试的代码要少得多。其次,如果文档的结构发生变化,那么更改 XPath 查询要比更改一堆代码容易得多。
Of course, you have to learn XPath, but (most of) XPath isn't rocket science.
当然,您必须学习 XPath,但(大部分)XPath 不是火箭科学。
PHP's DOM uses the xpath_evalmethod to perform XPath queries. It's documented here, and the user notes include some pretty good examples.
PHP 的 DOM 使用该xpath_eval方法来执行 XPath 查询。它记录在此处,用户注释包括一些非常好的示例。
回答by Robert Rossney
Here's another (lazy) way to do it.
这是另一种(懒惰的)方法。
$data[][$node->nodeName] = $node->nodeValue;
回答by Daniele Orlando
With FluidXMLyou can query and iterate XML very easly.
使用FluidXML,您可以非常轻松地查询和迭代 XML。
$data = [];
$store_child = function($i, $fooChild) use (&$data) {
$data[] = [ $fooChild->nodeName => $fooChild->nodeValue ];
};
fluidxml($dom)->query('//foo/*')->each($store_child);

