Creation of XML File in PHP with SimpleXML

Basic information about XML :

What is XML ?

XML Stands for Extensible Markup Language. A markup language is used to annotate text or add additional information.

XML is a universal format for structured documents and data on web. It allows you to separate content from formatting.

Note :- I assume that you have basic idea what XML Files are.

Starting with the tutorial :-

As we are going to generate XML File with SimpleXML, there is a basic requirement to use SimpleXML.

Prerequisites :

This extension requires the libxml PHP extension. This means that passing in –enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default. The SimpleXML extension requires PHP 5.0 .

Installation :

This extension is enabled by default. It may be disabled by using the following option at compile time: –disable-simplexml

Note: Before PHP 5.1.2, –enable-simplexml is required to enable this extension.

1. Creating Object of  SimpleXML :

$xmlstr =  <<<XML
<?xml version='1.0' encoding=’UTF-8’?>
			<title>Movie Details</title>
						<actor>Imran Hashmi</actor>
						<actor>Nargis Fakri</actor>
					All is revealed in this controversial spoof of a documentary.
					<line>PHP solves all my web problems</line>
				<rating type="thumbs">7</rating>
				<rating type="stars">5</rating>

	//SimpleXML Object created
$movies = new SimpleXMLElement($xmlstr);

2. Adding child Node :

Adds child element to XML node

Syntax :-

addChild ( string $name [, string $value [, string $namespace ]] )

It takes following parameters,

  1. Name:- Name of the child node to be added
  2. Value:- Value of the child node (optional)
  3. Namespace:- Namespace to which the child element belongs (optional)

Returns:- The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

Example :-

$xmlstr = "<?xmlversion='1.0' encoding='UTF-8'?><movies></movies>";

//Creating SimpleXML Object

$movies = new SimpleXMLElement($xmlstr);

//Adding child to movies node (name:actorName and value:Brad Pitt)
	$movies->addChild(‘actorName’,’Brad Pitt’);


<?xmlversion='1.0' encoding='UTF-8'?>
		<actorName>Brad Pitt</actorName>

3. Adding attribute to node :

Adds an attribute to XML element

Syntax :-

addAttribute (string $name [, string $value [, string $namespace ]] )

It takes following parameters,

  1. Name :- Name of the attribute to add
  2. Value :- Value of the attribute (optional)
  3. Namespace :- Namespace to which the attribute belong (optional)

Returns :- No value is returned.
Example :-

$xmlstr="<?xml version='1.0' encoding='UTF-8'?><news></news>";

//Creating SimpleXML Object
$newsXML = new SimpleXMLElement($xmlstr);

//Setting the newsPagePrefix attribute and its value to the news node
$newsXML->addAttribute('newsPagePrefix', 'Times of India');


<?xmlversion='1.0' encoding='UTF-8'?>
	<news newspagePrefix=”Times of India”>

4. Saving XML File :

Returns well-formed XML string based on SimpleXML element.

Syntax :-

asXML ([string $filename] )  OR  saveXML ([string $filename] )

It takes following parameter,

  1. Filename :- the function writes the data to the file rather than returning it. (optional)

The asXML method formats the parent object’s data in XML version 1.0.

Returns :- If the filename isn’t specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Example :-

//Saving XML File
$movies->asXML(); OR 
$movies->saveXML(); OR

5. Using CDATA Section:

What is CDATA ? what does it do ? How it is useful ?

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup.

We can also say that, CDATA are defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup.

The predefined entities such as &lt;, &gt;, and &amp; require typing and are generally difficult to read in the markup. In such cases, CDATA section can be used. By using CDATA section, you are commanding the parser that the particular section of the document contains no markup and should be treated as regular text.

Now to use CDATA in Your XML File, You need to create a class extending the SimpleXMLElement class and in that create a wrapper/helper function for CDATA.

Example Using CDATA Section :-

//Saving XML File

Output :- File Name : lead-details.xml

//Creating custom class and extending the SimpleXMLElement Class

Class SimpleXMLElementExtended extends SimpleXMLElement {
 *     Adds a child with $value inside CDATA 
	public function addChildWithCDATA($name, $value = NULL) { 
		$new_child = $this->addChild($name); 
		if ($new_child !== NULL) { 
		$node = dom_import_simplexml($new_child);
		$no=$node->ownerDocument; $node->appendChild($no->createCDATASection($value)); 
	return $new_child; 

$xmlstr ="<?xml version='1.0' encoding='UTF-8'?><lead></lead>";

**Note :- As we are using CDATA we will be creating object of SimpleXMLElementExtended Class.

<?xml version='1.0' encoding='UTF-8'?>


References :-

For XML File Generation using SimpleXML




Leave a Reply

Your email address will not be published. Required fields are marked *