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’?>
	<movies>
		<movie>
			
			<title>Movie Details</title>
				
				<characters>
				
					<character>
						<name>Azhar</name>
						<actor>Imran Hashmi</actor>
					</character>
				
					<character>
						<name>Sangeeta</name>
						<actor>Nargis Fakri</actor>
					</character>
					
				</characters>
				
				<plot>
					All is revealed in this controversial spoof of a documentary.
				</plot>
			
				<great-lines>
					<line>PHP solves all my web problems</line>
				</great-lines>
				
				<rating type="thumbs">7</rating>
				<rating type="stars">5</rating>
		</movie>
	</movies>
XML;

	//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’);

Output:

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

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');

Output:

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

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
$movies->asXML(“movie-details.xml”);

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
$leadRootNode->saveXML(“lead-details.xml”);

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'?>

	<lead>
	
		<firstName><![CDATA[Dipesh]]></firstName>
		<lastName><![CDATA[Pandya]]></lastName>
		
		<leadId><![CDATA[120921]]></leadId>
		<leadIP><![CDATA[192.168.1.1]]></leadIP>
		<newBuild><![CDATA[No]]></newBuild>
		<firstTimeBuyer><![CDATA[Yes]]></firstTimeBuyer>
		
	</lead>

References :-

For XML File Generation using SimpleXML

  1. http://php.net/manual/en/book.simplexml.php

For CDATA

  1. http://stackoverflow.com/questions/2784183/what-does-cdata-in-xml-mean
  2. http://www.tutorialspoint.com/xml/xml_cdata_sections.htm