PHP : Read Write XML with SimpleXML

In this article, I will be showing you how to create and read xml document with php’s SimpleXML extension.

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

Below is the code to create XML file. I have named the output file ‘example.xml’. For better understanding, I have written comment for almost every line of code.


<?php

// GENERATING XML NODE

// Create new SimpleXMLElement object
$itemsXml = new SimpleXMLElement("<items></items>");

// Add child element the SimpleXML element
$itemXml = $itemsXml->addChild('item');

// Add attribute to the SimpleXML element
$itemXml->addAttribute('id', 1);
$itemXml->addAttribute('type', 'simple');

$mobileXml = $itemXml->addChild('Mobiles');

// Suppose we have the following array of data
$items = array(array('name'=>'nokia','weight'=>'2'),
                array('name'=>'samsung','weight'=>'5'),
                array('name'=>'sony','weight'=>'3'));

foreach ($items as $item)
{
    // XML PART
    // Please look carefully on the variable names. They are important for using addChild method.
    $brandXml = $mobileXml->addChild('Brand');
    $nameXml = $brandXml->addChild('Name',$item['name']);
    $weightXml = $brandXml->addChild('Weight',$item['weight']);
}

// FOR PROPER FORMATTING XML

// Create a new DOMDocument object
$doc = new DOMDocument('1.0');

// add spaces, new lines and make the XML more readable format
$doc->formatOutput = true;

// Get a DOMElement object from a SimpleXMLElement object
$domnode = dom_import_simplexml($itemsXml);

$domnode->preserveWhiteSpace = false;

// Import node into current document
$domnode = $doc->importNode($domnode, true);

// Add new child at the end of the children
$domnode = $doc->appendChild($domnode);

// Dump the internal XML tree back into a string
$saveXml = $doc->saveXML();

// SET HEADER TO OUTPUT DATA

header('HTTP/1.1 200 OK');
header("Pragma: no-cache");
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Content-type', 'text/xml');
header('Content-Disposition: attachment; filename="example.xml"');

echo $saveXml;

?>

The following xml file is created. The xml file is named example.xml.


<?xml version="1.0"?>
<items>
  <item id="1" type="simple">
    <Mobiles>
      <Brand>
        <Name>nokia</Name>
        <Weight>2</Weight>
      </Brand>
      <Brand>
        <Name>samsung</Name>
        <Weight>5</Weight>
      </Brand>
      <Brand>
        <Name>sony</Name>
        <Weight>3</Weight>
      </Brand>
    </Mobiles>
  </item>
</items>

Here is the code to read the xml file.
I have mentioned two ways to read the xml file. The first one loads the xml file, converts the data into string and prints it.


<?php

// Get SimpleXMLElement object from an XML document
$xml = simplexml_load_file("example.xml");

// Get XML string from a SimpleXML element
// When you select "View source" in the browser window, you will see the objects and elements
echo $xml->asXML();

?>

The second way is to loop through the xml content and print. It’s more specific.


<?php

// Get SimpleXMLElement object from an XML document
$xml = simplexml_load_file("example.xml");

// Get the name of a SimpleXML element
echo "<b>Root Element:</b> <br/>";
echo $xml->getName();
echo "</p>";

// get the attribute of 'item' element
// Get SimpleXML element's attributes
$attribute = $xml->item->attributes();

// $attribute is an object
// looping through the object and printing the attribute name and value
echo "<p><b>Attributes:</b> (of element 'item')<br/>";
foreach($attribute as $key => $value) {
    echo $key . " = " . $value . "<br/>";
}
echo "</p>";

// Get the children of a specified node
$children = $xml->children();
// echo "<pre>"; print_r($children);

foreach($children as $child) {
    // get mobiles brands
    $mobiles = $child->Mobiles->Brand;

    // print brand name
    echo "<p><b>Brands:</b><br/>";
    foreach($mobiles as $key => $value) {
        echo $value->Name . "<br/>";
    }
    echo "</p>";
}

?>

Hope it helps. Thanks.