HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP XML

XML (Extensible Markup Language) is a data format used to store and transport data. While JSON has become more popular in recent years, XML is still widely used in many legacy systems, RSS feeds, and enterprise web services. PHP provides several ways to parse XML, with **SimpleXML** being the most user-friendly.


The SimpleXML Parser

SimpleXML is a PHP extension that allows you to easily convert XML data into an object that you can navigate like any other PHP object.

1. Parsing XML from a String

If you have XML data stored in a variable, you can use simplexml_load_string().

<?php
    $myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>";

    $xml = simplexml_load_string($myXMLData);
    
    echo $xml->to;      // Outputs: Tove
    echo $xml->heading; // Outputs: Reminder
?>

2. Parsing XML from a File

If your XML data is in a file (e.g., note.xml), use simplexml_load_file().

<?php
    $xml = simplexml_load_file("note.xml");
    echo $xml->to;
?>

Looping Through XML

If your XML has multiple elements (like a list of books), you can use a foreach loop to iterate through them.

<?php
    $xml = simplexml_load_file("books.xml");
    foreach($xml->children() as $book) {
        echo $book->title . " by " . $book->author . "<br>";
    }
?>

Accessing Attributes

To access attributes of an XML tag, you use array syntax on the object property.

<?php
    // XML: <book id='1'>...</book>
    echo $xml->book[0]['id']; // Outputs the 'id' attribute of the first book
?>
Tip: SimpleXML is great for reading XML. If you need to create complex XML documents from scratch, you might want to look into the **DOMDocument** class.

Summary

  • XML is used for structured data storage and transport.
  • SimpleXML is the easiest way to read XML in PHP.
  • simplexml_load_string() parses XML from a variable.
  • simplexml_load_file() parses XML from a file.
  • XML elements are accessed as object properties.
Note: If the XML is invalid or poorly formatted, SimpleXML will return false and generate warnings. Always check your XML source!

What's Next?

Handling data often involves making sure it is safe and valid. Let's explore how to protect your application in the **PHP Filters & Validation** lesson.