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.
What Is SimpleXML?
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:
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);
Example XML File
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>
Loading an XML File with SimpleXML
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>";
}
?>
Explanation
-
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
Loading XML from a String
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.
Accessing XML Elements
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>";
}
Accessing XML Attributes
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>";
}
Adding New Elements in XML
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.
Modifying Existing XML Data
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!";
?>
Deleting XML Elements
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!";
?>
Handling Errors While Loading XML
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.
SimpleXML Functions Summary
| 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 |
Common Mistakes to Avoid
-
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.
Advantages of SimpleXML
-
Very easy to use and read
-
Converts XML to PHP objects automatically
-
Suitable for small and medium files
-
Supports both reading and writing
When to Avoid SimpleXML
-
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)
Summary of the Tutorial
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:
For small projects, configuration files, or XML-based APIs, SimpleXML is a reliable and efficient choice.