2012-03-03 76 views
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'); 

它扔像

Fatal error: Call to undefined method DOMNodeList::replaceChild() 

cheat.xml错误看起来像

理解问题
<?xml version="1.0"?> 
<matches> 

      <match id="2204"> 

    <Game></Game> 

     <team1sabbr></team1sabbr> 

     <team2sabbr></team2sabbr> 
+1

什么是'$ oldNode'?它在哪里定义? – 2012-03-03 08:23:36

+0

@Martin哦......我刚刚从某处复制了代码并使用它,请问您能否展示如何定义它。谢谢。 – krishna 2012-03-03 08:34:01

+0

在这种情况下,我可能会收到此错误,以及 – krishna 2012-03-03 08:39:06

回答

5

您需要修改您的代码如下所示:通过每个找到的元素

  • $team1sabbr = $dom->getElementsByTagName('team1sabbr'); 
    $textNode = $dom->createTextNode('value-1'); 
    
    foreach ($team1sabbr as $team) { 
        $team->parentNode->replaceChild($textNode, $team); 
    } 
    
    1. 迭代找到元素
    2. 父节点上使用replaceChild的父母。

    编辑::
    通过的意见,似乎问题是不清楚。

    以下是需要的。

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

    的作品,但一个小问题就来了,比如' 值-1 ',而不是' 值-1 '这是没有标签的其打印只是孩子值 – krishna 2012-03-03 10:06:11

    +0

    @BVKrishna:那是因为你使用'createTextNode',不知道你的期望。如果您需要标签,请使用'createElement'。是否只是想替换** teamsabbr1中的值**?矿石 Leigh 2012-03-03 10:14:49

    +0

    更换整个部件我只是更改了引用代码'createElement'和我得到的是''代替'值-1' – krishna 2012-03-03 10:19:33

    2

    $team1sabbrDOMNodeList,即列表Node s,而不是一个Node。你需要选择其中的一个。

    +0

    谢谢背后的原因。你能否写下这样做的方式。我已经放置了'cheat.xml'的格式。 – krishna 2012-03-03 08:31:35

    +0

    @BVKrishna:如果您确定只有一个''的实例,您可以执行'$ team1sabbr [0] - > ...'。 – 2012-03-03 08:32:44

    +0

    雅'team1sabbr'仅仅是一个例子,但我其他一些具有两个实例 – krishna 2012-03-03 08:35:49