简体   繁体   English

使用simpleXML重命名多个属性

[英]rename multiple attributes with simpleXML

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

I'm trying to rename multiple "name" attributes at once: 我试图一次重命名多个“名称”属性:

$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);

Returns: 返回值:

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 )

How can I get php to save the New values back to the XML? 如何获取php将新值保存回XML? Does it need another foreach loop? 是否需要另一个foreach循环? The code seems to be getting too complex already. 代码似乎已经变得太复杂了。

I'm trying this, but no dice: 我正在尝试,但没有骰子:

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

Simplexml is buid to returns node only. Simplexml是buid,仅返回节点。 That's weird, but '/root/gallery/@name' and '/root/gallery' . 那很奇怪,但是'/root/gallery/@name''/root/gallery'

These two queries 这两个查询

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

will return the same instances 将返回相同的实例

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

So the only way for changing the attribute of a node is with the array syntaxe 因此,更改节点属性的唯一方法是使用数组语法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM