2010-05-16 29 views
10

Esto me está volviendo loco ... Solo quiero agregar otro nodo 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(); 

error:

+0

'$ xmlDoc-> getElementsByTagname ('album') [0];' ahora funciona en PHP7 :) –

Respuesta

21

DOMDocument :: getElementsByTagName no devuelve una matriz, devuelve un DOMNodeList. Es necesario utilizar el método item acceder a sus artículos:

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

mmmm: Error fatal: No se puede usar el objeto del tipo DOMNodeList como matriz en/Applications/XAMPP/xamppfiles/htdocs/admin /tests/DOMDoc.php en la línea 18 – FFish

+0

¡¡Hurra !! Muchas gracias Matti. – FFish

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

no puedes hacer esto en php

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

que tiene que hacer esto

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

EDIT: getElementsByTagname devuelve un objeto para que pueda hacer esto (el código anterior está en correcta) ...

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

Este error ....

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

DOMNodeList imposible tener un método appendChild. DOMNode lo hace.

Cuestiones relacionadas