如何使用 php 更新特定节点的 XML 元素


How to update XML element for a particular node using php?

<?xml version="1.0" encoding="UTF-8"?>
<FLOOR>
  <FLOOR1>
<BlOCK ID="F5" NAME="HallMark" URL="F1.COM"/>
<BlOCK ID="F6" NAME="F6" URL="F1.COM"/>
<BlOCK ID="F7" NAME="U.S. Polo Assn." URL="F1.COM"/>
  </FLOOR1>
    <FLOOR2>
<BlOCK ID="G4" NAME="Daiso" URL="G1.COM"/>
<BlOCK ID="G5" NAME="Lakhoos Exchange" URL="G1.COM"/>
<BlOCK ID="G6" NAME="4u" URL="G1.COM"/>
<BlOCK ID="G7" NAME="Aldo" URL="G1.COM"/>
<BlOCK ID="G8" NAME="Athlete's co." URL="G1.COM"/>
    </FLOOR2>
</FLOOR>

以上是我的XML文件。我想用 ID =G8 更新"name"的元素值或说 ID=F7 .请帮忙。我尝试了很多代码。但失败了

I tried this .. but it returns empty.
$xmlFile = file_get_contents('floormap.xml');
//$xml = simplexml_load_string($xmlFile);
$new= new SimpleXMLElement($xmlFile);
$n=$new->xpath('//FLOOR1/B1OCK[@ID="F1"]');
var_dump($n);

你已经走了一半。这样做:

$xml = simplexml_load_string($x); // assume XML in $x
$update = $xml->xpath("//BlOCK[@ID='G7']")[0]; // requires PHP >= 5.4
$update['NAME'] = "Michi";

如果您现在查看$xml,则具有ID='G7'<BlOCK>节点的NAME -属性已更改。

看到它的工作原理:http://codepad.viper-7.com/F9Pte1