gpt4 book ai didi

php - 如何通过xpath获取每个节点的属性

转载 作者:行者123 更新时间:2023-12-03 17:06:28 25 4
gpt4 key购买 nike

如何通过xpath获取每个节点的属性?

例如,

book.xml,

<?xml version="1.0" encoding="UTF-8" ?>
<records timestamp="1264777862">
<record></record>
<record></record>
<record timestamp="1264777000"></record>
<record></record>
</records>


php,

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

# get and output "<entry>" elements
$x = $doc -> getElementsByTagName('record');

# Count the total feed with xpath.
$total = $x->length;

# the query is relative to the records node
$query = 'string(/records/@timestamp)';

for ($i=0; $i<$total; $i++)
{
$timestamp = $xpath->evaluate($query,$x->item($i));
echo $timestamp ."<br/>";
}

?>


结果(仅循环第一个节点),

1264777862
1264777862
1264777862
1264777862


但我想得到

1264777862
1264777000


我已经按照 here的问题和答案进行了修改。

也许有更好的方法?

编辑:

xml,

<?xml version="1.0" encoding="UTF-8" ?>
<records>
<record timestamp="1264777862">A</record>
<record>B</record>
<record timestamp="1264777000">C</record>
<record>D</record>
</records>


有了这个,

for ($i=0; $i<$total; $i++)
{
$value = $x->item($i)->childNodes->item(0)->nodeValue;
$timestamp = $xpath->evaluate($query,$x->item($i));
echo $value.': '.$timestamp ."<br/>";
}


我得到这个结果,

A: 1264777862
B: 1264777862
C: 1264777862
D: 1264777862


但这是我追求的结果

A: 1264777862
B:
C: 1264777862
D:


编辑:

一个测试,

$nodes = $xpath->query('//records/record');

foreach($nodes as $node) {
$value = $node->nodeValue;
$timestamp = $node->getAttribute('timestamp');
echo $value .': '."<br/>";
}


结果,

A: 
B:
C:
D:

最佳答案

一种方法:

$nodes = $xpath->query('//records[@timestamp]');
foreach($nodes as $node) {
$timestamp = $node->getAttribute('timestamp');
}


不过,您在示例中混合了 recordrecords,因此我不确定您实际使用的是哪个。



更新:此代码对我有用:

<?php

$xml = <<<EOL
<?xml version="1.0" encoding="UTF-8" ?>
<records>
<record timestamp="1264777862">A</record>
<record>B</record>
<record timestamp="1264777000">C</record>
<record>D</record>
</records>
EOL;

$x = new DOMDocument();
$x->loadXML($xml);

$xp = new DOMXpath($x);

$nodes = $xp->query('//records/record');
foreach($nodes as $node) {
echo $node->nodeValue, ': ', $node->getAttribute('timestamp'), "\n";
}


和输出

A: 1264777862
B:
C: 1264777000
D:

关于php - 如何通过xpath获取每个节点的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8067578/

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