Create a basic XML document with SimpleXML

Following on from yesterdays post, you can also use SimpleXML to quickly create XML documents.

The example below creates a very short and basic XML document containing a list of cars that I would love to have in my dream garage (well, some of them anyway).

$vehicles = array(
		"car1" => array(
			"make" => "BMW",
			"model" => "M3",
			"capacity" => "2500 c.c.",
			"fuel" => "Petrol"
		),
		"car2" => array(
			"make" => "Alfa Romeo",
			"model" => "155 V6 TI DTM",
			"capacity" => "2500 c.c.",
			"fuel" => "Petrol"
		),
		"car3" => array(
			"make" => "Ferrari",
			"model" => "F40",
			"capacity" => "2936 c.c.",
			"fuel" => "Petrol"
		)
	);
	
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><dreamgarage></dreamgarage>');
$xml->addAttribute('version', '1.0'); //add a version attribute
$xml->addChild('generated', date('Y-m-d H:i:s')." ".date_default_timezone_get());
	
$xml->addChild('owner', 'Denis');
$cars = $xml->addChild('cars');

foreach($vehicles as $vehicle) // loop through all vehicles in the garage array
{
	$car = cars->addChild('car'); // add a child car node for that vehicle
	
	foreach($vehicle as $key => $value) // loop through all attributes of each vehichle and add a child nodes for each vehicle attribute
	{		
		if($key == "fuel") //treat fuel type differently to all other key value pairs 
		{
			$children = $car->children();
			$children->capacity->addAttribute($key,$value); //add the fuel type as an attribute of the engine capacity node
		}
		else
		{
			$car->addChild($key, $value); //add the key value pair as a child node of car.
		}
	}
}

$location = $xml->addchild('location');
$location->addchild('country', 'Ireland');
$location->addChild('town', 'Limerick');
	
$xml->asXML('demo.xml'); //save xml to file (use asXML() with no arguments to display clean XML rather than output to file.)
    
    

The resulting XML looks like this.

<dreamgarage version="1.0">
    <generated>2013-10-21 20:04:51 UTC</generated>
    <owner>Denis</owner>
    <cars>
        <car>
            <make>BMW</make>
            <model>M3</model>
            <capacity fuel="Petrol">2500 c.c.</capacity>
        </car>
        <car>
            <make>Alfa Romeo</make>
            <model>155 V6 TI DTM</model>
            <capacity fuel="Petrol">2500 c.c.</capacity>
        </car>
        <car>
            <make>Ferrari</make>
            <model>F40</model>
            <capacity fuel="Petrol">2936 c.c.</capacity>
        </car>
    </cars>
    <location>
        <country>Ireland</country>
        <town>Limerick</town>  
    </location>   
</dreamgarage>


You can run this script here and you can view the output XML file here. The time in the “generated” node will be updated every time the script is run.