私は、複数の外部ソースから経済的および社会的統計を取得し、それらをデータベース(データ解析のため)に取り込むプログラムを作成しています。データの一部はXML形式で提供され、解析するためにXMLファイル内の要素/タグと属性を識別する必要があります。属性を識別するために、私はgetAttributeを使って試しました。DOMオブジェクトからのgetAttributeが属性を返さない
問題:getElementsByTagNameは機能しますが、getAttributeは機能しません。セル要素から属性 'Index'の値を取得しようとすると、属性「Index」がいくつかのセル要素に存在するにもかかわらず、「」が返されます。エラーはなく、値は返されません。
私はPHPマニュアルを読んで解決策を見つけようとインターネットを研究するのに数日を費やしましたが、成功しませんでした。 getAttributeの戻り値をエコーまたはvar_dumpすると、常に ""が返されます。 ソースコード全体を入れるのではなく、属性(この場合は 'Index'属性)を返すことができないという同じ問題を持つXMLファイルを読み込む簡単なバージョンを再現しました。すべてのヘルプは大歓迎されます
<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>
:ここ
<?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>";
}
}
?>
は、属性「インデックス」はないのgetAttributesで返されていないにもかかわらず、存在することを示しているXMLファイルのサンプルです。私は解決策を要約し、他の人を助けるために再投稿します。
あなたは 'DOMXpath :: evaluate()'も見てみることをお勧めします。 Xpathを使用すると、DOMドキュメントからデータを読みやすくなります。 – ThW