[英]How to convert a PHP DOMElement into a PHP DOMNodeList
I have a situation where I have a little function like below...我有一种情况,我有一个像下面这样的小功能......
public function childUpdate($nodes, $newValue) {
//Update values of each node
foreach ($nodes as $child) {
$child->nodeValue = $newValue;
}
}
This works perfectly whenever my function is sent a DOMNodeList
but occasionally it can be sent a DOMElement
instead.每当我的函数被发送一个DOMNodeList
时,这都能完美地工作,但有时它可以被发送一个DOMElement
。
This is a problem as in that situation, the foreach ($nodes as $child) {
line fails as foreach
does not work on a single element, and requires a list.这是一个问题,因为在这种情况下, foreach ($nodes as $child) {
行失败,因为foreach
不适用于单个元素,并且需要一个列表。
So my question is -- is there an elegant way to quickly convert a DOMElement
into a DOMNodeList
with just that one element inside it?所以我的问题是——有没有一种优雅的方法可以将DOMElement
快速转换为DOMNodeList
其中只有一个元素?
The obvious first thought is to wrap the DOMElement
inside an array like array(DOMElement)
, and while that works for this function above, it does fail in other situations where I rely on DOMNodeList
specific features.显而易见的第一个想法是将DOMElement
包装在像array(DOMElement)
这样的array(DOMElement)
,虽然这适用于上面的这个函数,但在我依赖DOMNodeList
特定功能的其他情况下它确实失败了。
A simple way to convert DOMElement
into a DOMNodeList
would really simplify my code and remove a lot of "if 'element' do this, this 'list' do that" conditions.将DOMElement
转换为DOMNodeList
一种简单方法将真正简化我的代码并删除很多“如果‘元素’执行此操作,此‘列表’执行此操作”条件。
Having the same problem.有同样的问题。
With advice from: How to add elements to DOMNodeList in PHP?来自以下方面的建议: 如何在 PHP 中向 DOMNodeList 添加元素?
Create a DOMDocument, add the DOMElement to it, and get childNodes which is a DOMNodeList创建一个 DOMDocument,向其中添加 DOMElement,并获取 childNodes,它是一个 DOMNodeList
if(!property_exists($data,'length')) {
$doc = new DOMDocument();
$elem = $doc->importNode($data);
$doc->appendChild($elem);
$nodeList = $doc->childNodes;
}
如果您有文档的 DOMXPath,则可以使用
$nodeList = $xpath->query(".", $node);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.