如何在PHP中向DOMNodeList添加元素? [英] How to add elements to DOMNodeList in PHP?

查看:133
本文介绍了如何在PHP中向DOMNodeList添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建自己的DOMNodeList?例如:

Is there a way to create my own DOMNodeList? E.g.:

$doc = new DOMDocument(); 
$elem = $doc->createElement('div');
$nodeList = new DOMNodeList; 
$nodeList->addItem($elem); // ?

我的想法是扩展DOMDocument类,添加一些有用的方法来将数据作为DOMNodeList返回。

My idea is to extend DOMDocument class adding some useful methods that return data as DOMNodeList.

是否可以在不编写自己的DOMNodeList类版本的情况下做到这一点?

Is it possible to do it without writing my own version of DOMNodeList class?

推荐答案

您不能将项目添加到 DOMNodeList 通过它的公共界面。但是,当DOMNodeLists连接到DOM Tree时,它们是活动集合,因此将子元素添加到DOMElement会在该元素的子集合中添加一个元素(这是DOMNodeList):

You cannot add items to DOMNodeList via it's public interface. However, DOMNodeLists are live collections when connected to a DOM Tree, so adding a Child Element to a DOMElement will add an element in that element's child collection (which is a DOMNodeList):

$doc = new DOMDocument();
$nodelist = $doc->childNodes; // a DOMNodeList
echo $nodelist->length;       // 0

$elem = $doc->createElement('div');
$doc->appendChild($elem);

echo $nodelist->length;       // 1

您说要添加一些将数据作为DOMNodeList返回的有用方法。在DOMDocument的上下文中,这就是 XPath 的作用。它允许您查询文档中的所有节点,并在DOMNodeList中返回它们。也许这就是您想要的。

You say you want to add "some useful methods that return data as DOMNodeList". In the context of DOMDocument, this is what XPath does. It allows you to query all the nodes in the document and return them in a DOMNodeList. Maybe that's what you are looking for.

这篇关于如何在PHP中向DOMNodeList添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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