addAttribute() to XML object

We can add attributes to different elements of XML object by using addAttribute() function. We will try with different examples to add attributes at different level of child node. We used asXML function to display XML string. We have used our sample xml file for this. Here is the code.

xml-sample1.php

<?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>

Adding attribute to different level of XML node.

We will only show the changed line here and the respective output
$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>


XML

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer