XML with PHP - SimpleXMLElement Class

PHP General Functions

XML is very common data format.

For example, the XML representation of a list:

<?xml version="1.0"?>
<list>
<item>eggs</item>
<item>bread</item>
<item>milk</item>
<item>bananas</item>
<item>cheese</item>
</list>

To produce the above XML using PHP, first create an array that will the list.

$list = array("eggs", "bread", "milk", "bananas", "cheese");

Then, a SimpleXMLElement object is instantiated with a root tag that forms the basis for the document.

$xml = new SimpleXMLElement("<list />");

In XML, everything has to be in a tag so an <item> tag has been introduced in order to contain each list item.

foreach($list as $item)
{
$xml->addChild("item", $item);
}

 

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive