请帮助我理解替换子节点的问题
$dom = new DOMDocument();
$dom->load('cheat.xml');
$team1sabbr = $dom->getElementsByTagName('team1sabbr');
$textNode = $dom->createTextNode('value-1');
$textNode = $dom->importNode($textNode, true);
$team1sabbr->replaceChild($textNode, $oldNode);
$dom->save('cheat.xml');
它抛出了一个类似的错误
Fatal error: Call to undefined method DOMNodeList::replaceChild()
cheat.xml
看起来像
<?xml version="1.0"?>
<matches>
<match id="2204">
<Game></Game>
<team1sabbr></team1sabbr>
<team2sabbr></team2sabbr>
您需要修改代码,使其看起来如下所示:
$team1sabbr = $dom->getElementsByTagName('team1sabbr');
$textNode = $dom->createTextNode('value-1');
foreach ($team1sabbr as $team) {
$team->parentNode->replaceChild($textNode, $team);
}
- 遍历找到的每个元素
- 定位该元素的父级
- 在父节点上使用
replaceChild
编辑::
通过评论,这个问题似乎并不清楚。
以下是所需内容。
$team1sabbr = $dom->getElementsByTagName('team1sabbr');
foreach ($team1sabbr as $team) {
$team->nodeValue = 'value-1';
}
$team1sabbr
是DOMNodeList
,即Node
的列表,而不是单个Node
。你需要从中挑选一个。