Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 2, to name="William" ? Or the title hi to hello ?

Thanks a lot for your atention, H'

like image 825
punkbit Avatar asked Mar 03 '10 11:03

punkbit


People also ask

How to add attribute in PHP?

You can easily add attribute to HTML tags using Regex and PHP. The preg_replace() function searches string matches to the pattern (regular expression) and replaces with replacement. Use preg_replace() function with regular expression to add attribute to HTML tag using PHP.

How to access xml attributes in PHP?

The PHP SimpleXML extension makes it easy to work with XML files by creating an object from the XML structure. To access an element's attributes, use the property() method for that element.


1 Answers

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)

like image 117
Gordon Avatar answered Oct 26 '22 20:10

Gordon