2010-05-16 63 views
10

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

$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(); 

错误:

+0

'$ xmlDoc-> getElementsByTagname('album')[0];'现在在PHP7中工作:) – 2016-04-01 15:36:18

回答

21

DOM文档的getElementsByTagName ::不返回数组,它返回一个DOMNodeList。您需要使用item方法来访问它的项目:

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

mmmm:致命错误:不能在/ Applications/XAMPP/xamppfiles/htdocs/admin中使用DOMNodeList类型的对象作为数组/tests/DOMDoc.php 18行 – FFish 2010-05-16 23:33:34

+0

Hooray !!非常感谢马蒂。 – FFish 2010-05-16 23:39:59

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呢。