How to convert any MySQL table and data to a well-formed XML document using PHP. Building a generic solution to a common problem.
In this tutorial we will create a standardized script that will convert a MySQL table of any shape or size into a valid XML document. This can be useful for any situation where you have to transfer data from a MySQL database into an XML based system. In some cases the "mysqldump –xml" might be sufficient. If you require output that’s different from the mysqldump format, or if you don’t have access to the mysqldump tool you will need to code your own solution. Creating a single-use script to handle specific data is of course quite easy, but would require custom coding for each table that needs to be converted to XML. I’m going to show you how (using a handy PHP function) you can build a more generalized solution. This mechanism will allow you to convert a MySQL table to XML, but also to a PHP array, CSV file (even though MySQL already supports CSV natively) or any other required format.
Let’s start with an example table and some data:
Table name: fruit +--------------+----------------+------------------+--------------+ | fruit_id | fruit_name | fruit_colour | price_per_kg | +--------------+----------------+------------------+--------------+ | 1 | Banana | yellow | 2,99 | | 2 | Orange | orange | 2,45 | | 3 | Strawberries | red | 4,99 | +--------------+----------------+------------------+--------------+
After running our PHP script the resulting XML will look like this:
<?xml version="1.0" encoding="UTF-8"?>
<fruits>
<fruit>
<fruit_id>1</fruit_id>
<fruit_name>Banana</fruit_name>
<fruit_colour>yellow</fruit_colour>
<price_per_kg>2,99</price_per_kg>
</fruit>
<fruit>
<fruit_id>2</fruit_id>
<fruit_name>Orange</fruit_name>
<fruit_colour>orange</fruit_colour>
<price_per_kg>2,45</price_per_kg>
</fruit>
<fruit>
<fruit_id>3</fruit_id>
<fruit_name>Strawberry</fruit_name>
<fruit_colour>red</fruit_colour>
<price_per_kg>4,99</price_per_kg>
</fruit>
</fruits>
Pretty neat huh?
So let’s get down to business and start by setting up our database connection:
<?php //database configuration $config['mysql_host'] = "localhost"; $config['mysql_user'] = "root"; $config['mysql_pass'] = "grape01"; $config['db_name'] = "fruit_store"; $config['table_name'] = "fruit"; //connect to host mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); //select database @mysql_select_db($config['db_name']) or die( "Unable to select database");
We start building the actual XML by creating the XML header and the necessary root element (which we derive from the table name, add “s” for plural!):
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $root_element = $config['table_name']."s"; //fruits $xml .= "<$root_element>";
And now for the actual fun stuff! We select the items from the table and use the mysql_fetch_assoc() function to return the query result as an associative array.
//select all items in table
$sql = "SELECT * FROM ".$config['table_name'];
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[$value]]>";
//and close the element
$xml .= "</$key>";
}
$xml.="</".$config['table_name'].">";
}
}
That’s it! We have created a list of XML elements representing the MySQL data. Now all we have to do is properly close the XML and output the data to (in this case) the browser:
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
header ("Content-Type:text/xml");
//output the XML data
echo $xml;
?>
The script can be easily modified to allow for different types of XML (think element names vs attributes). If the script is accessed through a URL we can make the script even more flexible by passing the table or column name(s) as a parameter. Always make sure that the SQL data doesn’t hold any (unicode) characters that are not allowed in XML! I will post a few more conversion examples in another post.
Please let me know if you have any questions or issues with the code using the comment form below.

This tutorial is very good for me to understand. But my need is not ‘only showing data on the browser’.
I need to write an urgent advanced code using the xml file with php and mySQL database.
How to produce physical xml file (not on the browser) from multiple tables?
How to read data from this physical xml file and save in the multiple tables?
Please kindly help me.
Hi Thet Thet,
in the example the generated XML is stored in the $xml variable before being sent to the browser. If you wanted to store the XML to a file instead you can use the standard PHP functions for file handling. Example:
To store data from an XML file into a database is a whole different story. Perhaps I’ll write another tutorial about that later. If you simply need to copy a database you’re better off using the mysqldump utility that comes with MySQL.
Hope this helps!
what to do if i need the php file to be dynamic? example it is sqlcovertxml.php..
i want that file to accommodate any SELECT statement. how?
Hi Karen,
how do you want the script to be dynamic? You could use a form to send a custom SQL statement to the script instead of predefining the query in the code.
The SQL statement can be adjusted into whatever you like as long as we get an associative array with (key,value) pairs as a result. It gets tricky if you want to join two or more tables, you’ll probably want to adjust the names of the root element and that of the main element of each result row in that case.
Hope this helps.
i wish to generate xml from 3 tables.The resulting file should look something like
how do i go about this?
You cannot post XML in the comments. Send me a sample using the contact form.
thanks, it’s helpful
very helpful article…..
it’s completely without any error..
Thanks Bhavesh!
thanks a lot for this… I am to generate it for my website… Thanks again
Hi All.
What a very simple, easy to follow, well written tutorial.
Very good.
Sorry, I’m having a little trouble.
I would like my code to appear just like yours! Unfortunaely, it looks different, and includes the following
Id there a way I can remove the CDATE just to display the following
Kind regards
Hi James, it looks like your code examples got filtered out. Can you try again? Or send me your full message including the code samples using the contact form.
how to save the xml file in a folder after generating it from database
Hi,
thank you, very helpfull.
Please juste one question, I don’t have a probleme but just would like to know, for the appearing inside the file .xml (i choose this option)how to down the line.
thanks again.
Hi …,first of all not write $result ,how to check the condition. if (!$result = mysql_query($sql))
die(“Query failed.”);
I altered the example somewhat to make it more readible.
This is giving me an error… “error on line 3 at column 6: XML declaration allowed only at the start of the document”
when I delete the ‘.’ before the = in that line, it works, but I only get the first entry…
Any ideas? Thanks
I was looking for a tutorial to read the contents from a table and lists them in XML format. This was the only one that worked right off the bat. Thank you!