2010-03-03 87 views
8

如果你有類似的東西,PHP SimpleXML,如何設置屬性?

<hello id="1" name="myName1"> 
<anotherTag title="Hello"> 
</anotherTag> 
</hello> 
<hello id="2" name="myName2"> 
<anotherTag title="Hi"> 
</anotherTag> 
</hello> 

如何改變的屬性,例如,你好ID 2,名稱=「威廉」?或標題嗨,你好?

非常感謝您的atention, H」

回答

15

記住,你的XML文檔必須有一個根元素:

$xml = simplexml_load_string("<root>$string</root>"); 
$xml->hello[1]['name'] = 'John Doe'; 
$xml->hello[1]->anotherTag['title'] = 'Hello'; 
echo $xml->asXml(); 

要保存文件使用asXML($filename)

1

如果你想使用simplexml在根元素上設置一個屬性,你可以這樣做:

$xml['name'] = "william"; 

但是,對於上面列出的示例,以前的海報是正確的;您需要添加頂級元素。

0
$xml[0]['name'] = "newname"; 

我相信這是另一種編輯XML文檔的方式。
我使用的這種方法將與提供的XML文件一起工作。
他可以像訪問「第一個」示例那樣以陣列形式訪問根標籤。
這可以讓他不必在標籤中停下來。