PHP XML Parsers


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.

What Is an XML Parser?

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

Why Use XML in PHP?

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.

Types of XML Parsers in PHP

PHP offers three main XML parsers, each with its own purpose and advantages.

  1. SimpleXML Parser – Best for reading and accessing data easily.

  2. Expat Parser – Fast and event-driven; ideal for large XML files.

  3. DOM Parser – Powerful for editing or creating XML documents.

Let’s understand each one with examples.

1. PHP SimpleXML Parser

What Is SimpleXML?

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.

Example

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>";
}
?>

Why Use SimpleXML?

  • Quick and easy to use

  • No complex setup or functions

  • Works best for smaller XML files

When Not to Use It

Avoid SimpleXML for very large XML files, as it loads the entire document into memory.

2. PHP XML Expat Parser

What Is Expat Parser?

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.

Example

<?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 to Use Expat 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)

3. PHP DOM Parser

What Is DOM Parser?

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.

Example

<?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>";
}
?>

Why Use DOM Parser?

  • You can add, edit, or delete XML nodes

  • Ideal for generating new XML files

  • Gives complete control over the XML structure

When to Avoid DOM Parser

Avoid it for very large XML files, as it consumes more memory by loading everything at once.

Comparison of XML Parsers in PHP

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

Example XML File for Practice

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>

Common Errors When Working with XML

  1. Invalid file path – Ensure the XML file path is correct.

  2. Unclosed tags – Each opening tag must have a closing tag.

  3. Special characters – Use proper encoding for symbols like & or <.

  4. Mixing parsers – Don’t mix SimpleXML with DOM or Expat functions.

  5. Improper permissions – Make sure PHP can read the XML file.

Best Practices for XML Parsing in PHP

  • 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.

Summary of the Tutorial

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.


Practice Questions

  1. 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.

  2. 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.

  3. Using SimpleXML, write a PHP script to load movies.xml and count how many <movie> elements exist in the file. Display the total count.

  4. Write a PHP script using Expat Parser that prints all start and end tag names from an XML file called employees.xml.

  5. 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.

  6. Using SimpleXML, access and print the value of the <age> tag of the first <student> in students.xml.

  7. 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”).

  8. Using Expat Parser, create handler functions that display tag names and their inner text when reading products.xml.

  9. 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.

  10. 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().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top