2010-05-16 60 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呢。