PHP XML Processing

๐Ÿ“œ PHP XML Processing – Read, Parse, and Modify XML Files

XML (Extensible Markup Language) is used to store and transport data. In PHP, we can easily process XML files using SimpleXML and DOMDocument.

Let’s explore how to read, parse, and modify XML files in PHP. ๐Ÿš€


๐Ÿ“Œ What is XML?

XML is like HTML’s strict cousin ๐Ÿค“. It stores data in a structured format.

Hereโ€™s a sample XML file:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Harry Potter</title>
        <author>J.K. Rowling</author>
    </book>
    <book>
        <title>The Hobbit</title>
        <author>J.R.R. Tolkien</author>
    </book>
</library>

Now, let’s process this XML using PHP!


๐Ÿ“ Example 1: Reading XML with SimpleXML

SimpleXML makes XML processing super easy! Let’s read our XML data:

<?php
$xml = simplexml_load_file("books.xml") or die("Error: Cannot load XML!");

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

Try It Now

๐Ÿ” Output:

Title: Harry Potter  
Author: J.K. Rowling  

Title: The Hobbit  
Author: J.R.R. Tolkien

๐Ÿ“ Example 2: Modifying XML with SimpleXML

Letโ€™s add a new book to our XML file.

<?php
$xml = simplexml_load_file("books.xml");

$newBook = $xml->addChild("book");
$newBook->addChild("title", "The Alchemist");
$newBook->addChild("author", "Paulo Coelho");

$xml->asXML("books.xml"); // Save changes
echo "New book added!";
?>

Try It Now

๐Ÿ“– This adds:

<book>
    <title>The Alchemist</title>
    <author>Paulo Coelho</author>
</book>

๐Ÿ“ Example 3: Reading XML with DOMDocument

DOMDocument gives more control over XML manipulation.

<?php
$doc = new DOMDocument();
$doc->load("books.xml");

$books = $doc->getElementsByTagName("book");

foreach ($books as $book) {
    $title = $book->getElementsByTagName("title")[0]->nodeValue;
    $author = $book->getElementsByTagName("author")[0]->nodeValue;
    echo "Title: $title <br> Author: $author <br><br>";
}
?>

Try It Now


๐ŸŽฏ Summary

  • โœ… XML stores structured data.
  • โœ… SimpleXML is easy to use for reading and modifying XML.
  • โœ… DOMDocument gives advanced XML manipulation options.

๐Ÿš€ Next Steps

Try modifying and extracting data from your own XML files! Happy coding! ๐ŸŽ‰