gpt4 book ai didi

php - PHP XML-找出已知值的路径

转载 作者:行者123 更新时间:2023-12-03 11:49:14 25 4
gpt4 key购买 nike

这是XML位:

[11] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 46e8f57e67db48b29d84dda77cf0ef51
[label] => Publications
)

[section] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 9a34d6b273914f18b2273e8de7c48fd6
[label] => Journal Articles
[recordId] => 1a5a5710b0e0468e92f9a2ced92906e3
)


我知道值“ 46e8f57e67db48b29d84dda77cf0ef51”,但其位置在文件中有所不同。我可以使用XPath查找该值的路径吗?如果没有,可以使用什么?

最新的试用版无效:

$search = $xml->xpath("//text()=='047ec63e32fe450e943cb678339e8102'");

while(list( , $node) = each($search)) {

echo '047ec63e32fe450e943cb678339e8102',$node,"\n";

}

最佳答案

PHP的DOMNode对象具有以下功能:DOMNode::getNodePath()

$xml = <<<'XML'
<root>
<child key="1">
<child key="2"/>
<child key="3"/>
</child>
</root>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$nodes = $xpath->evaluate('//child');

foreach ($nodes as $node) {
var_dump($node->getNodePath());
}


输出:

string(11) "/root/child"
string(20) "/root/child/child[1]"
string(20) "/root/child/child[2]"


SimpleXML是DOM的包装器,这是一个允许您获取SimpleXMLElement的DOMNode的函数: dom_import_simplexml

$xml = <<<'XML'
<root>
<child key="1">
<child key="2"/>
<child key="3"/>
</child>
</root>
XML;

$structure = simplexml_load_string($xml);
$elements = $structure->xpath('//child');

foreach ($elements as $element) {
$node = dom_import_simplexml($element);
var_dump($node->getNodePath());
}


要通过其属性获取元素,可以使用xpath。

在文档中的任何位置使用元素百搭器选择所有节点:

//*

通过id属性过滤它们:

//*[@id = "46e8f57e67db48b29d84dda77cf0ef51"]

$dom = new DOMDocument();
$dom->loadXml('<node id="46e8f57e67db48b29d84dda77cf0ef51"/>');
$xpath = new DOMXpath($dom);

foreach ($xpath->evaluate('//*[@id = "46e8f57e67db48b29d84dda77cf0ef51"]') as $node) {
var_dump(
$node->getNodePath()
);
}

关于php - PHP XML-找出已知值的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928367/

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