The addAttribute() function adds an attribute to the SimpleXML element.
PHP addAttribute() Function has the following syntax.
addAttribute(name,value,ns);
Parameter | Is Required | Description |
---|---|---|
name | Required. | Name of the attribute to add |
value | Optional. | Value of the attribute |
ns | Optional. | A namespace for the attribute |
No value is returned
Add an attribute to the root element and to the body element:
<?php/*w ww .j ava 2 s . c o m*/
$note=<<<XML
<book>
<name>PHP</name>
<name>Java</name>
</book>
XML;
$xml=new SimpleXMLElement($note);
$xml->addAttribute("type","private");
$xml->body->addAttribute("date","2013-01-01");
echo $xml->asXML();
?>
The code above generates the following result.