SimpleXMLElement

This is part of PHP core so no installation is required. This extension can be checked by using phpinfo().

Example 1 generate XML data

<?Php
header('Content-Type: text/xml');
$e = new SimpleXMLElement('<detils/>');


    $add = $e->addChild('address');
    $add->addChild('door_no', "Door_No: Abcd");
    $add->addChild('Street', "Street NO: 123 Abcd");

print($e->asXML());
?>
Output is here
<detils>
<address>
<door_no>Door_No: Abcd</door_no>
<Street>Street NO: 123 Abcd</Street>
</address>
</detils>

Example 2 generate XML by looping

<?Php
header('Content-Type: text/xml');
$e = new SimpleXMLElement('<detils/>');

for ($i = 1; $i <= 4; ++$i) {
    $add = $e->addChild('address');
    $add->addChild('door_no', "Door_No $i");
    $add->addChild('Street', "Street NO $i");
}
print($e->asXML());
?>
Output is here
<detils>
<address>
<door_no>Door_No 1</door_no>
<Street>Street NO 1</Street>
</address>
<address>
<door_no>Door_No 2</door_no>
<Street>Street NO 2</Street>
</address>
<address>
<door_no>Door_No 3</door_no>
<Street>Street NO 3</Street>
</address>
<address>
<door_no>Door_No 4</door_no>
<Street>Street NO 4</Street>
</address>
</detils>

Example 2: Parsing XML and Accessing Child Elements

Using SimpleXMLElement, we can access child elements of an XML document directly:

$xml_data = '<books><book><title>PHP Basics</title></book></books>';
$xml = new SimpleXMLElement($xml_data);
echo $xml->book->title; // Outputs: PHP Basics

Example 4: Looping Through Multiple Child Elements

Here’s how to loop through multiple elements in an XML structure:

$xml_data = '<books><book><title>PHP Basics</title></book><book><title>MySQL Guide</title></book></books>';
$xml = new SimpleXMLElement($xml_data);
foreach ($xml->book as $book) {
    echo $book->title . "<br>";
}
// Outputs:
// PHP Basics
// MySQL Guide

Example 5: Modifying XML Elements

You can modify the content of an XML element using SimpleXMLElement:

$xml->book[0]->title = "Advanced PHP";
echo $xml->asXML(); 
// Outputs the updated XML structure

Displaying XML data or creating XML file by using Database records

XML simpleXML_load_string()

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