PHP addAttribute() Function

Definition and Usage

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

This function has no return value.

Syntax

class SimpleXMLElement
{
string addAttribute(name,value,ns)
} 
Parameters Description
name Required. Specifies the name of the attribute.
value Required. Specifies the value of the attribute.
ns Optional. Specifies the namespace of the attribute.

Example

XML File:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP Code:

<?php
$xml = simplexml_load_file("test.xml");
$xml->body[0]->addAttribute("type", "small");
foreach($xml->body[0]->attributes() as $a => $b)
  {
  echo $a, '="', $b, '"';
  }
?>

Output:

type="small"