替换子节点值PHP-XML-DOM

kri*_*hna 1 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');
Run Code Online (Sandbox Code Playgroud)

它抛出的错误就像

Fatal error: Call to undefined method DOMNodeList::replaceChild()
Run Code Online (Sandbox Code Playgroud)

cheat.xml 好像

 <?xml version="1.0"?>
<matches>

            <match id="2204">

    <Game></Game> 

        <team1sabbr></team1sabbr> 

        <team2sabbr></team2sabbr>
Run Code Online (Sandbox Code Playgroud)

Lei*_*igh 5

您需要修改代码,如下所示:

$team1sabbr = $dom->getElementsByTagName('team1sabbr');
$textNode = $dom->createTextNode('value-1');

foreach ($team1sabbr as $team) {
    $team->parentNode->replaceChild($textNode, $team);
}
Run Code Online (Sandbox Code Playgroud)
  1. 遍历每个找到的元素
  2. 找到该元素的父元素
  3. 使用replaceChild父节点上.

编辑::
通过评论似乎问题不清楚.

以下是所需要的.

$team1sabbr = $dom->getElementsByTagName('team1sabbr');

foreach ($team1sabbr as $team) {
    $team->nodeValue = 'value-1';
}
Run Code Online (Sandbox Code Playgroud)