PHP addAttribute() Function

In this chapter you will learn:

  1. Description for PHP addAttribute() Function
  2. Syntax for PHP addAttribute() Function
  3. Parameter for PHP addAttribute() Function
  4. Return for PHP addAttribute() Function
  5. Example - Add an attribute to the root element and to the body element

Description

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//from   j  a v a2s.  c  om
$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.

Next chapter...

What you will learn in the next chapter:

  1. Description for PHP addChild() Function
  2. Syntax for PHP addChild() Function
  3. Parameter for PHP addChild() Function
  4. Return for PHP addChild() Function
  5. Example - adds a child element to the SimpleXML element
Home » PHP Tutorial » PHP SimpleXML Functions
PHP SimpleXMLElement Create
PHP addAttribute() Function
PHP addChild() Function
PHP asXML() Function
PHP attributes() Function
PHP children() Function
PHP SimpleXML count() Function
PHP getDocNamespaces() Function
PHP getName() Function
PHP getNamespaces() Function
PHP registerXPathNamespace() Function
PHP simplexml_import_dom() Function
PHP simplexml_load_file() Function
PHP simplexml_load_string() Function
PHP xpath() Function