Home » PHP, XML

PHP : Read Write Xml with SimpleXML

23 October 2009 931 views No Comment Popularity: 10% Share/Bookmark

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 "<p><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>";
}

?>

From Mukesh Chapagain's Blog | Post PHP : Read Write Xml with SimpleXML

Related posts:

  1. PHP : Read Write Xml with DOMDocument
  2. Magento: Read Write XML
  3. Magento: Very Useful Collection Functions
  4. W3C Validation: IFrame Error with XHTML 1.0 Strict Doctype
  5. Magento: Read config XML nodes

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.