Export Mysql Table in XML using php



This tutorial will go over how to download Mysql Table into XML file. This is Very useful for generating XML Data files when you have to work with javascript to get data.

<?php
$conn = mysql_connect('localhost', 'user_name','password');
mysql_select_db('database_name');
$xml = '';

//query the db
$query = mysql_query("SELECT col1, col2, col3, col4 FROM TableName");
    $xml .='<main>';
//loop through query results
while ( $row = mysql_fetch_array ( $query ) )
{
 //Add to xml
$xml .= '<group>';
 $xml .= '<col1><![CDATA[' . $row['col1'] . ']]></col1>'; 
$xml .= '<col2><![CDATA[' . $row['col2'] . ']]></col2>'; 
 $xml .= '<col3><![CDATA[' . $row['col3'] . ']]></col3>'; 
$xml .= '<col4 ><![CDATA[' . $row['col4 '] . ']]></col4 >'; 
$xml .= '</group>';
}

    $xml .='</main>'; 

//Write to xml and override
$handle = fopen('data.xml', 'w+');
fwrite($handle, $xml);
?>

Note:- Please Assign 777 permission to folder to write file into it.

0 comments :