2010-11-22 71 views
1
<root> 
    <gallery name="First"/> 
    <gallery name="Second"/> 
    <gallery name="Third"/> 
</root> 

我試圖重命名多個 「名」 屬性立刻:用SimpleXML重命名多個屬性

$rename = array(); 
foreach($_POST['name'] as $value) { 
    $rename[] = $value; 
} 

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true); 
$gallery = $objXML->xpath('/root/gallery/@name'); 
print_r($gallery); 
print_r($rename); 

$objXML->asXML(XML_FILE_NAME); 

返回:

Array ([0] => SimpleXMLElement Object ([@attributes] => Array ([name] => First)) [1] => SimpleXMLElement Object ([@attributes] => Array ([name] => Second)) [2] => SimpleXMLElement Object ([@attributes] => Array ([name] => Third))) 

Array ([0] => First New [1] => Second New [2] => Third New) 

我怎樣才能讓PHP保存新值返回到XML?它需要另一個foreach循環嗎?代碼似乎已經變得太複雜了。

我想這一點,但沒有骰子:

foreach($objXML->xpath('/root/gallery/@name') as $gallery) { 
    $gallery = $_POST['name']; 
} 
+0

我不看看'$ rename`在代碼 – stillstanding 2010-11-22 18:32:43

回答

1

simplexml的是打造專業化只返回節點。這很奇怪,但'/root/gallery/@name''/root/gallery'

這兩個查詢

$aList = $objXML->xpath('/root/gallery/@name'); 
$bList = $objXML->xpath('/root/gallery'); 

將返回相同的實例

for($i=0, $count=count($aList); $i<$count; $i++) { 
    $a = $aList[$i]; 
    $b = $aList[$i]; 
    var_dump($a==$b); // true 
} 

所以用於改變節點的屬性的唯一方法是與陣列syntaxe

foreach($aList as $node) { 
    $node['name'] = 'foo' . $i; 
} 
var_dump($objXML);