addAttribute() to XML object

Add attributes to an XML element

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.

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



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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer