我有一个XML文档,其基本结构如下:
<?xml version="1.0" encoding="UTF-8" ?>
<records timestamp="1264777862">
<record></record>
<record></record>
<record></record>
<record></record>
</records>
到目前为止,我一直在使用以下内容:
$doc = new DOMDocument();
$doc->load('myfile.xml');
$xpath = new DOMXPath($doc);
$timestamp = $xpath->query("/records@timestamp");
但是这给了我一个无效的表达错误。
用于获取根的timestamp属性的正确PHP / XPath表达式语法是什么?
答案 0 :(得分:2)
您现有的PHP代码是什么?你在使用DOMDocument吗? SimpleXML的?
正确的Xpath表达式是'string(/ records / @ timestamp)'
对于SimpleXML,请参阅http://php.net/manual/en/simplexmlelement.xpath.php e.g。
<?php
$string = <<<XML
<records timestamp="1264777862">
<record></record>
<record></record>
<record></record>
<record></record>
</records>
XML;
$xml = new SimpleXMLElement($string);
$result = $xml->xpath('string(/records/@timestamp)');
while(list( , $node) = each($result)) {
echo $node,"\n";
}
?>
对于DOMXPath,请参阅http://www.php.net/manual/en/domxpath.evaluate.php
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// our query is relative to the records node
$query = 'string(/records/@timestamp)';
$timestamp = $xpath->evaluate($query);
echo $timestamp ."\n";
?>
修改强>
见上面的编辑。需要在xpath表达式中转换为字符串