【发布时间】:2017-02-07 11:36:09
【问题描述】:
我正在编写一个程序,该程序从多个外部来源获取经济和社会统计数据,并将它们提取到数据库中(用于数据分析)。一些数据采用 XML 格式,为了解析它,我需要识别 XML 文件中的元素/标签以及属性。为了识别我尝试使用 getAttribute 的属性。
问题:虽然 getElementsByTagName 有效,但 getAttribute 无效。尝试从单元格元素中检索属性“索引”的值会返回“”,即使属性“索引”确实存在于许多单元格元素中。没有错误,只是没有返回值。
我花了几天时间阅读 PHP 手册并研究 Internet 以尝试找到解决方案,但没有成功。 getAttribute 的返回值上的回显或 var_dump 表明它始终返回“”。 我没有放整个源代码,而是复制了一个读取下面 XML 文件的更简单版本,它会遇到同样的问题,即无法返回属性(在本例中为“索引”属性)。
<?php
// Creates new DOMDocument
$dom = new DOMDocument();
// Loads XML file into DOMDocument
$dom->load('FRED_formatted_list.xml');
// Stores all the instances of the Row tag into $rows
$rows = $dom->getElementsByTagName('Row');
// Iterates through all the instances of the Row tag
foreach($rows as $row) {
// Stores all the instances of the Cell tag into $cells
$cells = $row->getElementsByTagName('Cell');
// Iterates through all the instances of the Cell tag
foreach($cells as $cell) {
// Checks if the Index attribute exists in the cell tag
if($cell->hasAttribute('Index')) {
// Stores the value of any instances of the Index attribute
$attr = $cell->getAttribute('Index');
// Prints the value of any instances of the Index attribute to screen
echo "Value of index attribute: " . $attr . "<br>";
}
// Check that the cell tags have been properly identified in the DOM Object
echo $cell->nodeValue . "<br>";
// Double checks whether any index values are even found and stored in $attr
var_dump($attr) . "<br>";
}
}
?>
这是一个 XML 文件的示例,它显示属性“索引”确实存在,即使 getAttributes 没有返回:
<Row>
<Cell><Data ss:Type="String">AAA</Data></Cell>
<Cell ss:Index="3"><Data ss:Type="String">Board of Governors of the Federal Reserve System (US)</Data></Cell>
<Cell><Data ss:Type="String">H.15 Selected Interest Rates</Data></Cell>
<Cell><Data ss:Type="String">Percent</Data></Cell>
<Cell><Data ss:Type="String">Not Seasonally Adjusted</Data></Cell>
<Cell><Data ss:Type="String">The Federal Reserve Board has discontinued this series as of October 11, 2016. More information, including possible alternative series, can be found at http://www.federalreserve.gov/feeds/h15.html. </Data></Cell>
</Row>
任何帮助将不胜感激。我将总结解决方案并重新发布以帮助他人。
【问题讨论】:
-
我建议你也看看
DOMXpath::evaluate()。使用 Xpath 可以更轻松地从 DOM 文档中读取数据。
标签: php xml getattribute