-
Hajipur, Bihar, 844101
Working with XML in PHP becomes much easier with SimpleXML. It’s a built-in PHP extension that lets you read and manipulate XML data without complex functions or event handlers.
The best part about SimpleXML is that it converts an XML document directly into an object. That means you can access XML elements just like you access array keys or object properties in PHP.
In this tutorial, we’ll explore how SimpleXML works, how to load and parse XML files, access element data, handle attributes, and even modify XML content.
SimpleXML is a tree-based XML parser introduced in PHP 5. It reads the entire XML document into memory and creates an object structure that represents the XML hierarchy.
This approach makes it simple to:
Read XML files
Access and loop through elements
Get values and attributes
Add or update nodes
Here’s the basic syntax to load an XML file:
simplexml_load_file("filename.xml");
Or to load an XML string:
simplexml_load_string($xmlData);
Let’s create a simple XML file called students.xml to work with:
<students>
<student id="1">
<name>Riya Sharma</name>
<age>20</age>
<course>Web Development</course>
</student>
<student id="2">
<name>Ananya Singh</name>
<age>22</age>
<course>Data Science</course>
</student>
<student id="3">
<name>Meera Patel</name>
<age>21</age>
<course>UI/UX Design</course>
</student>
</students>
The easiest way to load and parse an XML file is by using the simplexml_load_file() function.
Here’s a simple example:
<?php
$xml = simplexml_load_file("students.xml");
foreach ($xml->student as $student) {
echo "Name: " . $student->name . "<br>";
echo "Age: " . $student->age . "<br>";
echo "Course: " . $student->course . "<br><br>";
}
?>
simplexml_load_file() reads the XML and returns an object.
$xml->student accesses all <student> elements.
Each element inside <student> can be accessed directly, such as $student->name or $student->age.
Output:
Name: Riya Sharma
Age: 20
Course: Web Development
If you have XML content stored in a variable, use simplexml_load_string() instead.
<?php
$xmlData = '
<user>
<name>Neha Verma</name>
<email>neha@example.com</email>
</user>';
$xml = simplexml_load_string($xmlData);
echo "Name: " . $xml->name . "<br>";
echo "Email: " . $xml->email;
?>
This is useful when you get XML responses from APIs or external sources.
SimpleXML allows you to access elements directly using object notation.
For example:
echo $xml->student[0]->name; // Outputs: Riya Sharma
You can also loop through elements:
foreach ($xml->student as $student) {
echo $student->name . "<br>";
}
You can also read XML attributes using the attributes() function.
Example:
<?php
$xml = simplexml_load_file("students.xml");
foreach ($xml->student as $student) {
echo "ID: " . $student['id'] . " - " . $student->name . "<br>";
}
?>
Output:
ID: 1 - Riya Sharma
ID: 2 - Ananya Singh
ID: 3 - Meera Patel
You can even loop through all attributes dynamically:
foreach ($student->attributes() as $key => $value) {
echo "$key: $value<br>";
}
SimpleXML lets you add new elements, but you’ll need to save the XML afterward.
Example:
<?php
$xml = simplexml_load_file("students.xml");
$newStudent = $xml->addChild("student");
$newStudent->addAttribute("id", "4");
$newStudent->addChild("name", "Isha Kapoor");
$newStudent->addChild("age", "23");
$newStudent->addChild("course", "Cloud Computing");
$xml->asXML("students.xml");
echo "New student added successfully!";
?>
After running this code, a new student entry will be added to students.xml.
To update existing data, just change the node value and save the file.
Example:
<?php
$xml = simplexml_load_file("students.xml");
// Update Riya’s course
$xml->student[0]->course = "Full Stack Development";
$xml->asXML("students.xml");
echo "Student record updated successfully!";
?>
SimpleXML does not directly provide a delete function, but you can remove nodes using the DOM extension with SimpleXML.
Example:
<?php
$xml = simplexml_load_file("students.xml");
$dom = dom_import_simplexml($xml->student[1]);
$dom->parentNode->removeChild($dom);
$xml->asXML("students.xml");
echo "Second student removed successfully!";
?>
It’s good practice to check whether an XML file is valid or not before parsing.
Example:
<?php
libxml_use_internal_errors(true);
$xml = simplexml_load_file("students.xml");
if ($xml === false) {
echo "Failed to load XML file.<br>";
foreach (libxml_get_errors() as $error) {
echo $error->message . "<br>";
}
} else {
echo "XML loaded successfully!";
}
?>
This prevents PHP from throwing warnings if the XML file is missing or malformed.
| Function | Description |
|---|---|
simplexml_load_file() |
Loads an XML file into an object |
simplexml_load_string() |
Loads XML from a string |
addChild() |
Adds a new child element |
addAttribute() |
Adds a new attribute |
attributes() |
Returns an element’s attributes |
asXML() |
Outputs XML as a string or saves to a file |
Wrong file path – Always ensure the XML file exists in the correct directory.
Unclosed tags – XML is strict; every opening tag needs a closing tag.
Forgetting asXML() – If you add or modify XML data, call asXML() to save changes.
Not checking for errors – Always validate XML before parsing.
Using incorrect element names – XML is case-sensitive.
Very easy to use and read
Converts XML to PHP objects automatically
Suitable for small and medium files
Supports both reading and writing
For very large XML files (it loads the whole document into memory)
When you need complex XML validation or streaming
If you need more control over parsing events (use Expat instead)
The SimpleXML parser is the most beginner-friendly way to work with XML in PHP. It allows you to read, access, and modify XML elements with simple object notation.
You now know how to:
Load XML files and strings
Access elements and attributes
Add or modify nodes
Handle XML errors safely
For small projects, configuration files, or XML-based APIs, SimpleXML is a reliable and efficient choice.
Create a PHP script that loads students.xml using simplexml_load_file() and prints each student’s name and course in a formatted list.
Write a PHP program to count how many <student> elements exist in students.xml and print the total number.
Using SimpleXML, print only the name and course of the second student in the XML file.
In students.xml, each <student> has an id attribute. Write code to display each student’s ID with their name.
Write a PHP script that loads the following XML string using simplexml_load_string() and prints the <email> value.
<user><name>Neha</name><email>neha@example.com</email></user>
Using SimpleXML, add a new <student> element with name, age, and course details to students.xml and save the updated file.
Write a PHP script that updates the <course> value of the first student in students.xml to “Full Stack Development”.
For each <student> element, loop through all attributes dynamically and print both attribute names and their values.
Create a script that tries to load a missing or invalid XML file. Use libxml_use_internal_errors(true) to catch and display the errors instead of stopping execution.
Load students.xml using SimpleXML, then use asXML() to convert the data back to a string and print it inside <pre> tags for readable formatting.