PHP SimpleXML, how to set attributes?

旧巷老猫 提交于 2019-12-10 01:49:56

问题


if you've got something like,

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

How to change the attributes of, for example, hello id 2, to name="William" ? Or the title hi to hello ?

Thanks a lot for your atention, H'


回答1:


Remember, your XML document has to have a root element:

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

To save the file use asXML($filename)




回答2:


If you want to set an attribute on the root element using simplexml you would do this:

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

However, for the example listed the previous poster is correct; you need to add a top level element.




回答3:


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

I believe this is another way of editing the XML document you have there.
This method I use will work with the XML file provided.
He can access the root tag in array-form like he would in the "first" example.
This allows him to not have to go down in the tags.



来源:https://stackoverflow.com/questions/2370631/php-simplexml-how-to-set-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!