2012-04-15 105 views
0

我需要知道如何更改標記的內容(而不是屬性,只是內容)。我不需要這個父標籤內的內部標籤。我只需要在裏面放一些文字。下一個XML文件(替換 「1 Hello World」 的):SimpleXMLElement如何更改標記內容(值)

<config name="THIS" type="string">1. Hello World)</config> 
<config name="IS" type="string">2. Hello World!</config> 
<config name="SPARTA" type="string">3. Hello World?</config> 

// create simple xml object 
$xml = new SimpleXMLElement(file_get_contents('file.xml')); 

// new names and values 
$names = array('THIS', 'SPARTA'); 
$values = array('1. Good bye world(', '3. Good bye world?'); 

// replace here 
foreach($xml as $a => $xmlElement) { 
    $indexOfName = array_search($names, (string)$xmlElement['name']); 
    if ($indexOfName !== false) { 
      // here I need to replace the value (e.g. 1. Hello World)) of config 
      // with the attribute @name == $names[$i] with the new value 
      // $values[$i] (3. Good bye world?) 
    } 
} 

回答

1

我找到了臨時解決方案。它創建一個新的簡單的XML和複製那裏從目前簡單的XML所有東西與替換內容值

$newXml = new SimpleXMLElement('<' . $xml->getName() . '></' . $xml->getName() . '>'); 
foreach($xml as $a => $xmlElement) { 
    $attr = $newXml->addChild($a, 'New content of the tag'); 
    foreach($xmlElement->attributes() as $k => $v) { 
     $attr->addAttribute($k, $v); 
    } 
} 
echo $newXml->asXML(); 

但它的臨時性。我希望如果有人能生產出更好的解決方案

1

通常情況下,你需要的父元素或者,如果你知道父母的結構,你可以嘗試xpath。除此之外,你可能想嘗試這個黑客:

$xmlElement->{0} = $values[$indexOfName]; 
+0

我已經試過了。它沒有工作 – pleerock 2012-04-15 10:50:41