替换子节点值PHP-XML-DOM


replacing a child node value PHP-XML-DOM

请帮助我理解替换子节点的问题

$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);
}
  1. 遍历找到的每个元素
  2. 定位该元素的父级
  3. 在父节点上使用replaceChild

编辑::
通过评论,这个问题似乎并不清楚。

以下是所需内容。

$team1sabbr = $dom->getElementsByTagName('team1sabbr');
foreach ($team1sabbr as $team) {
    $team->nodeValue = 'value-1';
}

$team1sabbrDOMNodeList,即Node的列表,而不是单个Node。你需要从中挑选一个。