我刚刚开始用 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”。到底是怎么回事?