How to Read / Write XML File in PHP

In this code snippet, we will see how to read / write XML file using PHP.

What is XML?

XML stands for Extensible Markup Language. Which is used to structure, store and transfer data from one system to another. XML is similar to HTML, except that XML allows users to define their own tags. Several web technologies are written in XML (i.e, RSS Feeds).

Here is the example XML format,

<?xml version="1.0" encoding="UTF-8"?>
<customer_list>
    <customer>
        <firstname>Thomas</firstname>
        <lastname>Raj</lastname>
        <email>thomas.raj@example.com</email>
    </customer>
    <customer>
        <firstname>Manoj</firstname>
        <lastname>Sharma</lastname>
        <email>manoj.sharma@test.com</email>
    </customer>
    <customer>
        <firstname>Anil</firstname>
        <lastname>Nagar</lastname>
        <email>anil.nagar@example.com</email>
    </customer>
</customer_list>

The XML contains tags and attributes. In the above example, <customer_list> is a parent tag which includes a set of <customer> tags and that each tag contains <firstname>, <lastname> and <email> tags.

Read XML file with DOM library:

Here is the example PHP code to read a XML file using Document Object Model (DOM) library and update that data into database table,

<?php
$servername = 'localhost';
$username = 'root';
$password = 'welcome';
$dbname = 'xml_file';

// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
} 

$doc = new DOMDocument();
$doc->load( 'file.xml' );
$customers = $doc->getElementsByTagName('customer');
foreach( $customers as $customer ) {
    $firstname = $customer->getElementsByTagName('firstname')->item(0)->nodeValue;
    $lastname = $customer->getElementsByTagName('lastname')->item(0)->nodeValue;
    $email = $customer->getElementsByTagName('email')->item(0)->nodeValue;

    $sql = "INSERT INTO `user_details` (id, firstname, lastname, email) VALUES (NULL, '$firstname', '$lastname', '$email')";

    if ($conn->query($sql) === TRUE) {
        echo 'Customer '.$firstname.' data updated successfully<br>';
    } else {
        echo 'Error occured: ' . $conn->error;
    }
}
$conn->close();

The DOM library reads the entire XML document and show it as a tree of nodes.

Write XML file with DOM library:

Here is the example PHP code to fetch the data from the database and write that data on the XML file using the PHP library Document Object Model (DOM),

<?php
$servername = 'localhost';
$username = 'root';
$password = 'welcome';
$dbname = 'xml_file';

// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname, email FROM user_details";
$result = $conn->query($sql);
$customer_list = [];
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $customer_list[] = [
                    'firstname' => $row['firstname'],
                    'lastname' => $row['lastname'],
                    'email' => $row['email']
                ];
    }
}

$doc = new DOMDocument();
$doc->formatOutput = true; 
$doc->encoding = 'UTF-8';
$r = $doc->createElement('customer_list');
$doc->appendChild($r);

foreach($customer_list as $customer) {
    $c = $doc->createElement('customer');
    
    $firstname = $doc->createElement('firstname');
    $firstname->appendChild(
        $doc->createTextNode($customer['firstname'])
    );
    $c->appendChild($firstname);

    $lastname = $doc->createElement('lastname');
    $lastname->appendChild(
        $doc->createTextNode($customer['lastname'])
    );
    $c->appendChild($lastname);

    $email = $doc->createElement('email');
    $email->appendChild(
        $doc->createTextNode($customer['email'])
    );
    $c->appendChild($email);

    $r->appendChild($c);
}
 
echo $doc->saveXML();
$conn->close();

Read more: How to Read / Write CSV File in PHP

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *