PHP addAttribute() Function
Definition and Usage
The addAttribute() function adds an attribute to a SimpleXML element.
The function has no return value.
Syntax
class SimpleXMLElement { string addAttribute(name,value,ns) }
Parameter | Description |
---|---|
name | Required. Specify the name of the attribute. |
value | Required. Specify the value of the attribute. |
ns | Optional. Specify 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"