How to Read / Write XML File in PHP

In this code snippet, I am going to show you how to read the content from the XML file and update/write the content to the 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 sample XML format for the reference,

<?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 script, <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();

In the above code,

  • First, enabled the database connection using the PHP function mysqli() with the database server name, user name, password and database name.
  • Second, Created the object using the DOMDocument() function and opened the XML file by using the function load() with the file name.
  • Next, used the PHP function getElementsByTagName() to get the tag content.
  • Finally, updated the data into the database using the INSERT query.

Note: 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();

In the above Code,

  • Same like the before example, first, enabled the database connection using the PHP function mysqli() with the database server name, user name, password and database name.
  • Second, fetched data from the database table using the SELECT query.
  • Next, Created the object using the DOMDocument() function and write the XML file using the function createElement(), appendChild() and createTextNode().
  • Finally, used the saveXML() function to save the file.

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 *