PHP DOMDocument getElementsByTagname?

跟風遠走 提交于 2019-12-29 06:47:19

问题


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:


回答1:


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



回答2:


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

you cant do this in php

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

you have to do this

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

EDIT: getElementsByTagname returns an object so you can do this (above code is incorrect)...

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

This error....

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

DOMNodeList doesnt have an appendChild method. DOMNode does.



来源:https://stackoverflow.com/questions/2845908/php-domdocument-getelementsbytagname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!