This tutorial will help you to generate XML file dynamically using PHP and MySql. Xml data can be simple to maintain and quite easy to integrate with flash environment.
In this article i’ll explain you how to execute Mysql query and format the data into an XML format than save it on server.
Steps to Generate an XML file from Mysql database.
Step 1: Declare the header content type as text/xml
header(‘Content-Type: text/xml; charset=utf-8’);
Step 2: Make an Database connection.
1 2 3 4 5 |
$conn = mysql_connect('hostname', 'username', 'password'); if(! $conn ) { die('Could not connect: ' . mysql_error()); } |
Step 3: Write the xml code to generate xml data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $sql = 'SELECT * from Table Name'; mysql_select_db('database_name'); $retval = mysql_query( $sql, $conn ); $xml="<PRODUCTS>\n\t\t"; while($data=mysql_fetch_array($retval)) { $xml .="<PRODUCT>\n\t\t"; $xml .= "<PRODUCT_URL>http://www.example.com/products_id=1</PRODUCT_URL>\n\t\t"; $xml .= "<PRODUCT_NAME>Product Name</PRODUCT_NAME>\n\t\t"; $xml .= "<PRICE>100.00</PRICE>\n\t\t"; $xml .= "<SHIPMENT_COST>0</SHIPMENT_COST>\n\t\t"; $xml .= "<DELIVERY_TIME>Same Day</DELIVERY_TIME>\n\t\t"; $xml .= "<TAX>12.00</TAX>\n\t\t"; $xml.="</PRODUCT>\n\t"; } $xml.="</PRODUCTS>\n\r"; $xmlobj=new SimpleXMLElement($xml); $xmlobj->asXML('save.xml'); |
After execute this code, you will get the response as xml format and data will save on your server as save.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 |
<PRODUCTS> <PRODUCT> <PRODUCT_URL> http://www.example.com/products_id=1 </PRODUCT_URL> <PRODUCT_NAME>Product Name</PRODUCT_NAME> <PRICE>100.00</PRICE> <SHIPMENT_COST>0</SHIPMENT_COST> <DELIVERY_TIME>Same Day</DELIVERY_TIME> <TAX>12.00</TAX> </PRODUCT> </PRODUCTS> |
Note :- If you are using an http url as string in xml data with & symbol in between. It will give an error to string can not be parsed. Use & instead of & symbol in xml data.
Using above steps you can easily generate and save an xml file from Mysql data.