gpt4 book ai didi

php - 使用 DOMDocument PHP 获取 Xpath 父节点?

转载 作者:可可西里 更新时间:2023-11-01 12:37:31 24 4
gpt4 key购买 nike

我需要在 php 中获取特定节点的父节点。我正在使用 DOMDocument 和 XPath。我的 XML 是这样的:

<ProdCategories>
<ProdCategory>

<Id>138</Id>

<Name>Parent Category</Name>

<SubCategories>

<ProdCategory>

<Id>141</Id>

<Name>Category child</Name>

</ProdCategory>
</SubCategories>
</ProdCategory>
</ProdCategories>

PHP代码:

$dom = new DOMDocument();
$dom->load("ProdCategories_small.xml");
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//ProdCategory/Id[.="141"]/parent::*')->item(0);
print_r($nodes);

打印出来的是:

 DOMElement Object ( 
[tagName] => ProdCategory [schemaTypeInfo] => [nodeName] => ProdCategory [nodeValue] => 141 Category child [nodeType] => 1 [parentNode] => (object value omitted) [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => (object value omitted)

[parentNode](省略对象值),为什么?我会得到

    <Id>138</Id>

<Name>Parent Category</Name>`

最佳答案

The [parentNode] is (object value omitted), why?

这是因为您使用了 print_r function并创建这样的输出 ( via an internal helper function of the dom extension )。创建它的代码行是:

print_r($nodes);

print_rvar_dump 时,DOMNode 给出字符串“(省略对象值)”用于它。它告诉您,该字段(名为 parentNode)的对象 value 没有显示,而是被省略了。

从该消息中,您可以得出结论,该字段的值是一个对象。对类名的简单检查可以验证这一点:

echo get_class($nodes->parentNode), "\n"; # outputs  "DOMElement"

将其与整数或(空)字符串的字段进行比较:

[nodeType] => 1
...
[prefix] =>
[localName] => ProdCategory

所以我希望这能为您解决问题。只需访问该字段即可获取父节点对象:

$parent = $nodes->parentNode;

完成。

如果您想知道 PHP 给您的某个字符串,并且您觉得它可能是内部的东西,您可以在 http://lxr.php.net/ 上快速搜索所有 PHP 代码库。 , here is an example query for the string in your question .

关于php - 使用 DOMDocument PHP 获取 Xpath 父节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31335713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com