12

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'

Gordon
  • 312,688
  • 75
  • 539
  • 559
punkbit
  • 7,347
  • 10
  • 55
  • 89

3 Answers3

20

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)

Gordon
  • 312,688
  • 75
  • 539
  • 559
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.

Adam
  • 21
  • 2
1
$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.