PHP DOMDocument getElementsByTagname?

时间:2010-05-16 23:25:37

标签: php dom domdocument

这让我疯狂......我只想添加另一个img节点。

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<gallery>
    <album tnPath="tn/" lgPath="imm/"  fsPath="iml/" >
    <img src="004.jpg" caption="4th caption" />
    <img src="005.jpg" caption="5th caption" />
    <img src="006.jpg" caption="6th caption" />
</album>
</gallery>
XML;

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);

$album = $xmlDoc->getElementsByTagname('album')[0];
// Parse error: syntax error, unexpected '[' in /Applications/XAMPP/xamppfiles/htdocs/admin/tests/DOMDoc.php  on line 17
$album = $xmlDoc->getElementsByTagname('album');
// Fatal error: Call to undefined method DOMNodeList::appendChild() in /Applications/XAMPP/xamppfiles/htdocs/admin/tests/DOMDoc.php on line 19

$newImg = $xmlDoc->createElement("img");
$album->appendChild($newImg);

print $xmlDoc->saveXML();

错误:

2 个答案:

答案 0 :(得分:21)

DOMDocument :: getElementsByTagName不返回数组,它返回DOMNodeList。您需要使用item方法访问其项目:

$album = $xmlDoc->getElementsByTagname('album')->item(0);

答案 1 :(得分:0)

// Parse error: syntax error, unexpected '[' in /Applications/XAMPP/xamppfiles/htdocs/admin/tests/DOMDoc.php  on line 17

你不能在php

中这样做
$album = $xmlDoc->getElementsByTagname('album')[0];

你必须这样做

$albumList = $xmlDoc->getElementsByTagname('album');
$album = $albumList[0];

编辑: getElementsByTagname返回一个对象,以便您可以执行此操作(上面的代码不正确)...

$album = $xmlDoc->getElementsByTagname('album')->item(0);

此错误....

// Fatal error: Call to undefined method DOMNodeList::appendChild() in /Applications/XAMPP/xamppfiles/htdocs/admin/tests/DOMDoc.php on line 19

DOMNodeList没有appendChild方法。 DOMNode。

相关问题