Generate XML

XML files are used for various functionalities.

We can develop XML files by using PHP.

If you have to develop very small project, you can use XML files for saving data instead of MySQL or any other databse with PHP, which will be easy for maintaining and response time will be reduced.


I am listing a simple example.

<?php



$doc = new DOMDocument();

$doc->formatOutput = true;



//$p = new domElement('products');

$p = $doc->createElement( "products" );

$doc->appendChild( $p );





$c = $doc->createElement( "product" ); 

$c->setAttribute("id", 1);



$t = $doc->createElement( "title" );

$c->appendChild( $t );	

$t->nodeValue =htmlentities('bike');	





$r = $doc->createElement( "reviews" );

$c->appendChild( $r );



$re = $doc->createElement( "review" ); 

$re->setAttribute("id", 'r1');



$t = $doc->createElement( "title" );

$re->appendChild( $t );	

$t->nodeValue = "hello this is for testing";



$t = $doc->createElement( "desc" );

$re->appendChild( $t );	

$tmp = mb_convert_encoding("<b>test description</b>",'UTF-8','ISO-8859-1');	

$t->nodeValue = $tmp;



$t = $doc->createElement( "rating" );

$re->appendChild( $t );	

$t->nodeValue = 5;



$r->appendChild( $re );



$p->appendChild( $c );





//for saving file in directory

if($_REQUEST['f']=='s')

{

$flag = $doc->save('xml/products.xml');

if($flag)

{

echo 'Products XML generated successfully';

}

}

//for displaying

if($_REQUEST['f']=='d')

{

header("Content-Type: text/xml; charset=utf-8");

echo $doc->saveXML();	

}

//for downloading file

if($_REQUEST['f']=='a')

{

header("Pragma: public");

header("Expires: 0");

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("Cache-Control: private",false);

header ("Content-Type: application/xml;");

header("Content-Disposition: attachment; filename=products.xml;"); 

echo $doc->saveXML();

}

?>

In the above example I have used three ways for getting the XML file

1) You can save the generated XML in server (http://yoururl/filename.php?f=s).

2) Display the XML in the browser (http://yoururl/filename.php?f=d)

3) Popup for downloading the XML (http://yoururl/filename.php?f=a)


One thought on “Generate XML

  1. Perfect, thanks. Do you use lots of Magento themes? My company used a few that did a great deal to help to speed up page response times. It took a few months to get right and function to our needs but now it’s perfect. Saved hundreds on webserver costs by having it in a cloud vps. Thanks, Joellex.

Leave a Reply

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

Scroll to top