PHP SimpleXML, how to set attributes?

punkbit picture punkbit · Mar 3, 2010 · Viewed 17.2k times · Source

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'

Answer

Gordon picture Gordon · Mar 3, 2010

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)