PHP XML Parser

Reading and processing XML data in PHP

📄 What is XML Parser?

XML Parser reads and processes XML documents, allowing you to extract data from structured XML files. PHP provides multiple methods to parse XML including SimpleXML and DOM for different use cases.


<?php
// Simple XML parsing
$xml = simplexml_load_string('<note><to>John</to></note>');
echo $xml->to;
?>
                                    

Output:

John

XML Parsing Methods

SimpleXML

Easy XML parsing for simple tasks

simplexml_load_file() simplexml_load_string()
🌳

DOM Parser

Advanced XML manipulation

DOMDocument getElementsByTagName()
📖

XMLReader

Memory-efficient reading

XMLReader::open() read()
✍️

XMLWriter

Create XML documents

XMLWriter::startElement() writeElement()

🔹 SimpleXML - Load from String

Parse XML data from a string using simplexml_load_string(). This is the easiest way to work with XML when you have the XML content as a string variable.

<?php
$xmlString = '<?xml version="1.0"?>
<book>
    <title>PHP Basics</title>
    <author>John Doe</author>
    <price>29.99</price>
</book>';

$xml = simplexml_load_string($xmlString);
echo "Title: " . $xml->title;
echo "<br>Author: " . $xml->author;
echo "<br>Price: $" . $xml->price;
?>

Output:

Title: PHP Basics
Author: John Doe
Price: $29.99

🔹 SimpleXML - Load from File

Read XML data directly from a file using simplexml_load_file(). This method is perfect for processing XML configuration files or data feeds stored on disk.

<?php
// Assuming books.xml exists with book data
$xml = simplexml_load_file('books.xml');

foreach ($xml->book as $book) {
    echo "Title: " . $book->title . "<br>";
    echo "Author: " . $book->author . "<br><br>";
}

// Alternative: check if file loaded
if ($xml === false) {
    echo "Failed to load XML file";
}
?>

Output:

Title: PHP Basics
Author: John Doe

Title: Advanced PHP
Author: Jane Smith

🔹 Accessing XML Attributes

Extract attribute values from XML elements using array syntax. Attributes provide additional information about elements and are commonly used in XML documents.

<?php
$xmlString = '<?xml version="1.0"?>
<catalog>
    <product id="101" category="electronics">
        <name>Laptop</name>
        <price currency="USD">999</price>
    </product>
</catalog>';

$xml = simplexml_load_string($xmlString);
$product = $xml->product;

echo "Product ID: " . $product['id'];
echo "<br>Category: " . $product['category'];
echo "<br>Name: " . $product->name;
echo "<br>Price: " . $product->price . " " . $product->price['currency'];
?>

Output:

Product ID: 101
Category: electronics
Name: Laptop
Price: 999 USD

🔹 DOM Parser - Basic Usage

Use DOMDocument for more complex XML operations. DOM provides full control over XML structure, allowing you to modify, add, or remove elements and attributes.

<?php
$xmlString = '<?xml version="1.0"?>
<users>
    <user>
        <name>Alice</name>
        <email>[email protected]</email>
    </user>
    <user>
        <name>Bob</name>
        <email>[email protected]</email>
    </user>
</users>';

$dom = new DOMDocument();
$dom->loadXML($xmlString);

$users = $dom->getElementsByTagName('user');
foreach ($users as $user) {
    $name = $user->getElementsByTagName('name')[0]->nodeValue;
    $email = $user->getElementsByTagName('email')[0]->nodeValue;
    echo "Name: $name, Email: $email<br>";
}
?>

Output:

Name: Alice, Email: [email protected]
Name: Bob, Email: [email protected]

🔹 Creating XML with SimpleXML

Build XML documents programmatically using SimpleXML. You can create new elements, add attributes, and generate complete XML structures from PHP data.

<?php
// Create new XML document
$xml = new SimpleXMLElement('<catalog/>');

// Add book element
$book = $xml->addChild('book');
$book->addChild('title', 'Learning PHP');
$book->addChild('author', 'John Smith');
$book->addChild('year', '2024');
$book->addAttribute('isbn', '978-1234567890');

// Output formatted XML
echo htmlspecialchars($xml->asXML());
?>

Output:

<?xml version="1.0"?>
<catalog><book isbn="978-1234567890"><title>Learning PHP</title><author>John Smith</author><year>2024</year></book></catalog>

🔹 XPath Queries

Search XML documents using XPath expressions. XPath provides a powerful way to locate specific elements based on their path, attributes, or content within the XML structure.

<?php
$xmlString = '<?xml version="1.0"?>
<library>
    <book category="fiction">
        <title>The Great Novel</title>
        <price>15.99</price>
    </book>
    <book category="science">
        <title>Physics 101</title>
        <price>45.00</price>
    </book>
</library>';

$xml = simplexml_load_string($xmlString);

// Find all fiction books
$fiction = $xml->xpath('//book[@category="fiction"]');
foreach ($fiction as $book) {
    echo "Fiction: " . $book->title . "<br>";
}

// Find books under $20
$cheap = $xml->xpath('//book[price < 20]');
echo "Affordable: " . $cheap[0]->title;
?>

Output:

Fiction: The Great Novel
Affordable: The Great Novel

🔹 Error Handling

Handle XML parsing errors gracefully to prevent application crashes. Always validate XML input and check for parsing errors before processing the data.

<?php
$xmlString = '<invalid><xml>'; // Malformed XML

libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlString);

if ($xml === false) {
    echo "Failed to parse XML:<br>";
    foreach (libxml_get_errors() as $error) {
        echo "- " . $error->message . "<br>";
    }
    libxml_clear_errors();
} else {
    echo "XML parsed successfully";
}
?>

Output:

Failed to parse XML:
- Opening and ending tag mismatch: xml line 1 and invalid
- Premature end of data in tag invalid line 1

🧠 Test Your Knowledge

Which function loads XML from a string?