PHP SimpleXML, how to set attributes?
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 开发者_如何学C2, to name="William" ? Or the title hi to hello ?
Thanks a lot for your atention, H'
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)
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.
$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.
精彩评论