PHP で XML 操作をいじり始めたばかりで、予期しないことに遭遇しました。テスト入力として使用している XML は次のとおりです。
<list>
<activity1> running </activity1>
<activity2> swimming </activity2>
<activity3> soccer </activity3>
</list>
今、私はこのPHPコードが「activity1」を出力することを期待していました:
$xmldoc = new DOMDocument();
$xmldoc->load('file.xml');
//the line below would make $root the <list> node
$root = $xmldoc->firstChild;
//the line below would make $cnode the first child
//of the <list> node, which is <activity1>
$cnode = $root->firstChild;
//this should output 'activity1'
echo 'element name: ' . $cnode->nodeName;
代わりに、このコードは #text を出力します。ノード名を出力する前に、コードに新しい行を挿入することで修正できます。
$cnode = $cnode->nextSibling;
さて、代わりに「activity2」を印刷することを期待していましたが、「activity1」を印刷しています。何が起こっている?