Create xml file using simplexml php

Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

asked Sep 27, 2008 at 6:30

Sure you can. Eg.

");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output



    

Have fun.

answered Sep 27, 2008 at 7:42

DreamWerxDreamWerx

2,8781 gold badge18 silver badges13 bronze badges

6

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

Create xml file using simplexml php

Giacomo1968

25.2k11 gold badges69 silver badges97 bronze badges

answered Sep 27, 2008 at 8:50

PhiLhoPhiLho

39.9k6 gold badges94 silver badges132 bronze badges

2

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

answered Sep 27, 2008 at 10:01

Stefan GehrigStefan Gehrig

81.5k24 gold badges155 silver badges185 bronze badges

2

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 =  <<
	
		
			
			Movie Details
				
				
				
					
						Azhar
						Imran Hashmi
					
				
					
						Sangeeta
						Nargis Fakri
					
					
				
				
				
					All is revealed in this controversial spoof of a documentary.
				
			
				
					PHP solves all my web problems
				
				
				7
				5
		
	
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 = "";

//Creating SimpleXML Object

$movies = new SimpleXMLElement($xmlstr);

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

Output:

	
		Brad Pitt
	

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="";

//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:

	
	

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 <, >, and & 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 ="";

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


	
	
		
		
		
		
		
		
		
		
	

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