使用 PHP 的 SimpleXML 访问元素的父元素?
我正在迭代一组 SimpleXML 对象,但不知道如何访问每个对象的父节点。这就是我想要的:
$divs = simplexml->xpath("//div");
foreach ($divs as $div)
{
$parent_div = $div->get_parent_node(); // Sadly, there's no such function.
}
似乎必须有一个相当简单的方法来做到这一点。
I'm iterating through a set of SimpleXML objects, and I can't figure out how to access each object's parent node. Here's what I want:
$divs = simplexml->xpath("//div");
foreach ($divs as $div)
{
$parent_div = $div->get_parent_node(); // Sadly, there's no such function.
}
Seems like there must be a fairly easy way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以运行一个简单的 XPath 查询来获取它:
由于这是 Simplexml,它只有元素和属性节点,并且父节点只能是元素而不能是属性,因此可以使用缩写语法:(
通过: 常见 Xpath 秘籍 - SimpleXML 类型速查表(2013 年 2 月;作者 hakre)< /em> )
You could run a simple XPath query to get it:
And as this is Simplexml and it only has element and attribute nodes and a parent node can only be an element and never an attribute, the abbreviated syntax can be used:
(via: Common Xpath Cheats - SimpleXML Type Cheatsheet (Feb 2013; by hakre) )
请注意,您可以扩展 SimpleXML 来实现这一点。例如:
现在您所要做的就是首先修改用于创建 SimpleXMLElement 的代码:
最好的部分是 SimpleXML 将自动且透明地返回此文档的
my_xml
对象,因此您不必更改任何其他内容,这使得您的get_parent_node()
方法可链接:Note that you can extend SimpleXML to make it so. For example:
And now all you have to do is modify the code you use to create your SimpleXMLElement in the first place:
The best part is that SimpleXML will automatically and transparently return
my_xml
objects for this document, so you don't have to change anything else, which makes yourget_parent_node()
method chainable:如果没记错的话,
xpath()
调用将返回一个或多个SimpleXMLElements
。如果是这种情况,那么您也许可以使用以下内容:If memory serves, an
xpath()
call returns one or moreSimpleXMLElements
. If that's the case, then you may be able to use something like: