PHP SimpleXML, how to set attributes?

2019-06-16 15:20发布

问题:

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.