In this tutorial am going to show how to create xml file using php and mysql.This script is used to create xml file dynamically.this script will help when you need to create xml file in php and mysql.
SimpleXMLElement is represents an element in an XML document.
Please share your comments and feedback.Thanks.Please subscribe my updates via email.
Download Script
The content type of the response header must be set to "text/xml".
header ("content-type: text/xml");
The content type of the response header must be set to "text/xml".
header ("content-type: text/xml");
DB Connection in php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('database') or die(mysql_error());
Create XML
//Create XML and stored in your project folder
$xmlobj=new SimpleXMLElement($xml);
//Your file name
$xmlobj->asXML("text.xml");
$xmlobj=new SimpleXMLElement($xml);
//Your file name
$xmlobj->asXML("text.xml");
Full Source
<?php
//content type for XML
header ("content-type: text/xml");
//DB Connection
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('yourdatabase') or die(mysql_error());
//Create XML
$xml='<?xml version="1.0" encoding="UTF-8"?>';
//Query
$qr=mysql_query("SELECT * FROM `customers` order by id desc") or die(mysql_error());
$xml.='<userlist>';
while($res=mysql_fetch_array($qr))
{
//Change field names as per your requirement
$xml.='<user><name>'.$res['name'].'</name><city>'.$res['city'].'</city><state>'.$res['state'].'</state></user>';
}
$xml.='</userlist>';
//Display Content
echo $xml;
//Create XML and stored in your project folder
$xmlobj=new SimpleXMLElement($xml);
//Your file name
$xmlobj->asXML("text.xml");
?>
//content type for XML
header ("content-type: text/xml");
//DB Connection
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('yourdatabase') or die(mysql_error());
//Create XML
$xml='<?xml version="1.0" encoding="UTF-8"?>';
//Query
$qr=mysql_query("SELECT * FROM `customers` order by id desc") or die(mysql_error());
$xml.='<userlist>';
while($res=mysql_fetch_array($qr))
{
//Change field names as per your requirement
$xml.='<user><name>'.$res['name'].'</name><city>'.$res['city'].'</city><state>'.$res['state'].'</state></user>';
}
$xml.='</userlist>';
//Display Content
echo $xml;
//Create XML and stored in your project folder
$xmlobj=new SimpleXMLElement($xml);
//Your file name
$xmlobj->asXML("text.xml");
?>