Create an XML file with PHP

March 22, 2014 | Last tested: May 2015 | 1253 views | Comments

Create XML files using SimpleXMLElement in PHP.

For example.

Dynamically generate an XML file on the fly.

//prepare the data
$members = array(
	0 => array('Jackson','Barbara','27','F','Florida'),
	1 => array('Kimball','Andrew','25','M','Texas'),
	2 => array('Baker','John','28','M','Arkansas'),
	3 => array('Gamble','Edward','29','M','Virginia'),
	4 => array('Anderson','Kimberly','23','F','Tennessee'),
	5 => array('Houston','Franchine','25','F','Idaho'),
	6 => array('Franklin','Howard','24','M','California'),
	7 => array('Chen','Dan','26','M','Washington'),
	8 => array('Daniel','Carolyn','27','F','North Carolina'),
	9 => array('Englert','Grant','25','M','Delaware')
);

//create a new xml object
$xml = new SimpleXMLElement('<members/>');

//loop through the data, and add each record to the xml object
foreach($members AS $memberDetails){
    $member = $xml->addChild('member');
    $member->addChild('lastName', $memberDetails[0]);
    $member->addChild('firstName', $memberDetails[1]);
	$member->addChild('age', $memberDetails[2]);
	$member->addChild('sex', $memberDetails[3]);
	$member->addChild('location', $memberDetails[4]);
}

//set header content type
Header('Content-type: text/xml');

//output the xml file
print($xml->asXML());

Result:

Please mouse over here to view the image.

 

Generate and save an XML file named members.xml.

//prepare the data
$members = array(
	0 => array('Jackson','Barbara','27','F','Florida'),
	1 => array('Kimball','Andrew','25','M','Texas'),
	2 => array('Baker','John','28','M','Arkansas'),
	3 => array('Gamble','Edward','29','M','Virginia'),
	4 => array('Anderson','Kimberly','23','F','Tennessee'),
	5 => array('Houston','Franchine','25','F','Idaho'),
	6 => array('Franklin','Howard','24','M','California'),
	7 => array('Chen','Dan','26','M','Washington'),
	8 => array('Daniel','Carolyn','27','F','North Carolina'),
	9 => array('Englert','Grant','25','M','Delaware')
);

//create a new xml object
$xml = new SimpleXMLElement('<members/>');

//loop through the data, and add each record to the xml object
foreach($members AS $memberDetails){
    $member = $xml->addChild('member');
    $member->addChild('lastName', $memberDetails[0]);
    $member->addChild('firstName', $memberDetails[1]);
	$member->addChild('age', $memberDetails[2]);
	$member->addChild('sex', $memberDetails[3]);
	$member->addChild('location', $memberDetails[4]);
}

//save the xml file
$xml->asXML("members.xml");

Result:

Please mouse over here to view the image.

 

Related Tutorials


Must Read