2014-09-24 66 views
0

我試圖更新XML文檔。我從一個包含XML的字符串開始。PHP - 更新XML屬性

我加載該字符串SimpleXMLElement對象:

$xmlDoc = simplexml_load_string($my_xml_string);

我發現我想更新,像這樣一個節點:以

$node= $xmlDoc->xpath("//nodename[@node_attribute='{$search_attribute_value}']");

現在我想更新node_attribute屬性。我試圖做$node['node_attribute']=$new_attribute_value然而$node是它自己的對象,並且這不會更新$xmlDoc對象。

如何找到並更新$xmlDoc中的屬性值?

回答

2

您在那裏的$node實際上是一個節點數組。如果你知道你只得到了一個更新,您可以:

$node[0]['node_attribute'] = $new_attribute_value; 

更合適的可能是:

$nodes = $xmlDoc->xpath("//nodename[@node_attribute='{$search_attribute_value}']"); 
foreach ($nodes as $node) { 
    $node['node_attribute'] = $new_attribute_value; 
} 

和預期的一樣,一切都會更新。

+0

是的,向該節點添加索引的確有竅門。 '$ node [0] ['node_attribute'] = $ new_attribute_value;'不知道之前發生了什麼。 – 2014-09-24 04:47:44

+1

@ dev.e.loper還要注意,如果你的節點有一個文本部分,你將使用'$ node [0] - > {'0'}',就像這樣寫在[在這裏](https://eval.in /私營/ 50fd041d061d09)。 – 2014-09-24 04:49:12

0

未經測試,但您應該嘗試這樣。

$nodename->attributes()->node_attribute = $new_attribute_value;