【问题标题】:PHP DOMDocument getElementsByTagname?PHP DOMDocument getElementsByTagname?
【发布时间】:2011-02-20 05:08:59
【问题描述】:

这让我发疯...我只想添加另一个 img 节点。

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

错误:

【问题讨论】:

  • $xmlDoc-&gt;getElementsByTagname('album')[0]; 现在适用于 PHP7 :)

标签: php dom domdocument


【解决方案1】:

DOMDocument::getElementsByTagName 不返回数组,它返回DOMNodeList。您需要使用item 方法来访问其项目:

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

【讨论】:

  • mmmm:致命错误:无法在第 18 行的 /Applications/XAMPP/xamppfiles/htdocs/admin/tests/DOMDoc.php 中使用 DOMNodeList 类型的对象作为数组
  • 万岁!!非常感谢马蒂。
【解决方案2】:
// 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 可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多