-
Hajipur, Bihar, 844101
XML (Extensible Markup Language) is used to store and transport structured data. It’s a simple text-based format that helps different systems exchange information, even if they’re built on different technologies.
PHP provides several ways to read and work with XML files using XML parsers. These parsers help PHP understand XML tags, extract data, and even modify or generate XML content.
An XML parser is a tool or function that reads XML data and converts it into a form PHP can use. Without a parser, PHP would treat XML as plain text.
A parser helps:
Read XML structure
Access elements and attributes
Modify or add new elements
Handle large or nested XML files
XML is still used in APIs, web services, configuration files, and document formats. Even though JSON is common now, XML is preferred when data needs to be well-structured, validated, or hierarchical.
For example, this is a simple XML file:
<student>
<name>Riya Sharma</name>
<age>20</age>
<course>Web Development</course>
</student>
Each tag represents data that can easily be parsed and used in PHP.
PHP offers three main XML parsers, each with its own purpose and advantages.
SimpleXML Parser – Best for reading and accessing data easily.
Expat Parser – Fast and event-driven; ideal for large XML files.
DOM Parser – Powerful for editing or creating XML documents.
Let’s understand each one with examples.
The SimpleXML parser is the easiest and most common way to handle XML in PHP. It converts XML elements into objects, so you can access them like array elements or object properties.
It’s perfect for beginners and small-to-medium XML files.
Assume you have a file named students.xml:
<students>
<student>
<name>Riya Sharma</name>
<age>20</age>
<course>Web Development</course>
</student>
<student>
<name>Ananya Singh</name>
<age>22</age>
<course>Data Science</course>
</student>
</students>
Here’s how to read it using SimpleXML:
<?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>";
}
?>
Quick and easy to use
No complex setup or functions
Works best for smaller XML files
Avoid SimpleXML for very large XML files, as it loads the entire document into memory.
The Expat parser works differently. Instead of loading the entire XML file at once, it reads the file line by line. It triggers specific functions when it finds the start or end of an XML tag.
This makes it much faster and memory-efficient for large files or streaming data.
<?php
$parser = xml_parser_create();
function startTag($parser, $name, $attrs) {
echo "Start Tag: $name<br>";
}
function endTag($parser, $name) {
echo "End Tag: $name<br>";
}
function contents($parser, $data) {
echo "Data: $data<br>";
}
xml_set_element_handler($parser, "startTag", "endTag");
xml_set_character_data_handler($parser, "contents");
$fp = fopen("students.xml", "r");
while ($data = fread($fp, 4096)) {
xml_parse($parser, $data, feof($fp)) or
die("Error: " . xml_error_string(xml_get_error_code($parser)));
}
xml_parser_free($parser);
?>
When working with large XML files
When performance and memory are important
When you want to process XML data in real-time (like live data feeds)
The Document Object Model (DOM) parser reads the entire XML document and represents it as a tree structure in memory. Every element, attribute, and piece of text becomes a node that you can navigate, modify, or remove.
<?php
$dom = new DOMDocument();
$dom->load("students.xml");
$students = $dom->getElementsByTagName("student");
foreach ($students as $student) {
echo "Name: " . $student->getElementsByTagName("name")[0]->nodeValue . "<br>";
echo "Age: " . $student->getElementsByTagName("age")[0]->nodeValue . "<br>";
echo "Course: " . $student->getElementsByTagName("course")[0]->nodeValue . "<br><br>";
}
?>
You can add, edit, or delete XML nodes
Ideal for generating new XML files
Gives complete control over the XML structure
Avoid it for very large XML files, as it consumes more memory by loading everything at once.
| Parser Type | Easy to Use | Speed | Memory Usage | Best For |
|---|---|---|---|---|
| SimpleXML | Yes | Moderate | Low–Moderate | Reading small XML files |
| Expat | Moderate | Fast | Low | Large or streamed XML files |
| DOM | Moderate | Slow | High | Editing or generating XML |
You can use the following XML for all examples:
<students>
<student>
<name>Riya Sharma</name>
<age>20</age>
<course>Web Development</course>
</student>
<student>
<name>Ananya Singh</name>
<age>22</age>
<course>Data Science</course>
</student>
</students>
Invalid file path – Ensure the XML file path is correct.
Unclosed tags – Each opening tag must have a closing tag.
Special characters – Use proper encoding for symbols like & or <.
Mixing parsers – Don’t mix SimpleXML with DOM or Expat functions.
Improper permissions – Make sure PHP can read the XML file.
Always validate XML using an online validator before using it.
Use simplexml_load_file() only for trusted XML files.
Handle parsing errors with custom error messages.
Use meaningful tag names for better readability.
For large XML data, prefer Expat or incremental DOM parsing.
XML parsing is an important skill when working with structured data in PHP. Depending on your needs, you can choose:
SimpleXML for small files and quick access.
Expat Parser for large, real-time XML data.
DOM Parser for editing or creating XML files.
Each parser has its own strengths. Once you understand them, you can easily choose the one that fits your project.
Create an XML file named books.xml containing at least three book entries (title, author, and price). Then, write a PHP script using SimpleXML to display all book details in a browser.
You have an XML file called students.xml. Write a PHP program using DOM Parser to read and print the names of all students enrolled in the “Web Development” course.
Using SimpleXML, write a PHP script to load movies.xml and count how many <movie> elements exist in the file. Display the total count.
Write a PHP script using Expat Parser that prints all start and end tag names from an XML file called employees.xml.
Create a PHP script using DOM Parser to add a new <student> element to the existing students.xml file. Include <name>, <age>, and <course> tags inside it.
Using SimpleXML, access and print the value of the <age> tag of the first <student> in students.xml.
Write a PHP program using DOM Parser to modify the <course> value of a specific student (for example, change “Web Development” to “Full Stack Development”).
Using Expat Parser, create handler functions that display tag names and their inner text when reading products.xml.
Write a PHP script using SimpleXML to check if the XML file orders.xml exists before loading it. If not, print a custom error message.
Create a PHP script using DOM Parser that reads an XML file and saves all element names in an array, then prints the array in readable format using print_r().