PHP Function Reference

PHP SimpleXMLElement - addAttribute() Method



The PHP SimpleXMLElement::addAttribute() method adds an attribute to the SimpleXML element.

Syntax

public SimpleXMLElement::addAttribute(qualifiedName, value, namespace)

Parameters

qualifiedName Required. Specify the name of the attribute to add.
value Required. Specify the value of the attribute.
namespace Optional. If specified, the namespace to which the attribute belongs.

Return Value

No value is returned.

Example:

The example below shows the usage of SimpleXMLElement::addAttribute() method.

<?php
$xmlstr = <<<XML
<userlist> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
  </user>
</userlist> 
XML;

$xml = simplexml_load_string($xmlstr);

$xml->addAttribute('type', 'games');

$user = $xml->addChild('user');
$user->addAttribute('id', 'Marry2015');
$user->addAttribute('game', 'group');

$name = $user->addChild('name', 'Marry G.');

$city = $user->addChild('city', 'London');

echo $xml->asXML();
?>

The output of the above code will be similar to:

<userlist type="games"> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
  </user>
  <user id="Marry2015" game="group">
    <name>Marry G.</name>
    <city>London</city>
  </user>
</userlist>

❮ PHP SimpleXML Reference