Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DOMDocument getElementsByTagname?

This is driving me bonkers... I just want to add another img node.

$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:

like image 337
FFish Avatar asked May 16 '10 23:05

FFish


People also ask

What is DOMDocument() in PHP?

The DOMDocument::getElementsByTagName() function is an inbuilt function in PHP which is used to return a new instance of class DOMNodeList which contains all the elements of local tag name.

How to get element by name in PHP?

The DOMElement::getElementsByTagName() function is an inbuilt function in PHP which is used to get the elements by tagname. Parameters: This function accepts a single parameter $name which holds the tag name or use * for getting all the tags.

What is getElementsByTagName?

The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node.


1 Answers

DOMDocument::getElementsByTagName doesn't return an array, it returns a DOMNodeList. You need to use the item method to access its items:

$album = $xmlDoc->getElementsByTagname('album')->item(0);
like image 54
Matti Virkkunen Avatar answered Oct 02 '22 15:10

Matti Virkkunen