使用simpleXML重命名多个属性

时间:2010-11-22 18:26:42

标签: php simplexml

<root>
  <gallery name="First"/>
  <gallery name="Second"/>
  <gallery name="Third"/>
</root>

我正在尝试一次重命名多个“name”属性:

$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将New值保存回XML?它需要另一个foreach循环吗?代码似乎已经变得太复杂了。

我正在尝试这个,但没有骰子:

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

1 个答案:

答案 0 :(得分: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
}

因此,更改节点属性的唯一方法是使用数组语法

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