addAttribute() attaches an attribute to the selected SimpleXMLElement node.
<?php
$xml = new SimpleXMLElement('<book/>');
$xml->addAttribute('id', '101');
$xml->addChild('title', 'PHP XML');
echo $xml->asXML();
?>Current example first; the detailed examples below are retained for additional learning and comparison.
<?php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
$main1->addAttribute('type', 'student');
echo $main1->asXML();
?>
Output is here.
<?xml version="1.0" standalone="yes"?>
<details type="student">
<name>Abcd</name>
<address>
<door_no>234-ac</door_no>
<street>Great Wall</street>
<city>Alabama</city>
</address>
</details>
$main1->address->addAttribute('type', 'local');
<address type="local">
Now adding to another node
$main1->address->street->addAttribute('type', 'main');
<street type="main">Great Wall</street>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.