PHP Tutorial - PHP addAttribute() Function






The addAttribute() function adds an attribute to the SimpleXML element.

Syntax

PHP addAttribute() Function has the following syntax.

addAttribute(name,value,ns);

Parameter

ParameterIs RequiredDescription
nameRequired.Name of the attribute to add
valueOptional.Value of the attribute
nsOptional.A namespace for the attribute

Return

No value is returned





Example

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.