Create XML File

PHP Programming

PHP Programming Examples

<?php
	/* Create object of 'SimpleXMLElement' to represents an element in an XML document. */
	$xml = new SimpleXMLElement('<xml/>');
	
	/* Adds a child element to the XML node */
	$customer = $xml->addChild('customer');
	
	/* Adds a child elements to the customer node */
	$customer->addChild("name", "James");
	$customer->addChild("email", "[email protected]");
	$customer->addChild("requirement", "Website");
	
	/* Adds a child element to the XML node */
	$customer = $xml->addChild('customer');
	
	/* Adds a child elements to the customer node */
	$customer->addChild("name", "Jonny");
	$customer->addChild("email", "[email protected]");
	$customer->addChild("requirement", "Android App");
	
	/* Set header */
	header('Content-type: text/xml; charset=utf-8');
	
	/* Put all the xml contents in a file */
	file_put_contents("customers.xml",$xml->asXML());
	
	echo "Xml file created successfully!";
?>


          /****** Output ******/
          

<?xml version="1.0"?>


<xml>


<customer>


<name>James</name>


<email>[email protected]</email>


<requirement>Website</requirement>


</customer>


<customer>


<name>Jonny</name>


<email>[email protected]</email>


<requirement>Android App</requirement>


</customer>


</xml>


Learn more about SimpleXMLElement, SimpleXMLElement::addChild, SimpleXMLElement::asXML and file_put_contents