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