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'
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With