Export MySql Into XML

Previously I just want to export several tables of my database from one server to another server. Let say, I want to send tables from server A to server B. In this case, I just make a php file that will generate xml file when executed. In this case, the php file to Export MySql Into XML will be placed in server A.

Here the codes:

//connecting to DB
$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$conn = mysql_connect($host, $user, $pass)
or die('Connection Failed');//will show "Connection Failed" if the connection failed
$db_name = 'member';//declare the database that will be used
mysql_select_db($db_name);//selecting the data base

//tables that will be exported
$tables = array("client","ib");

header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="'.$table.'.xml"');

$text ='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<'.$db_name.'>';

foreach($tables as $table){
	$result = mysql_query("SELECT * FROM  `$table`");
	$text .='
	<table_'.$table.'>';

	while($row=mysql_fetch_array($result)) {
		$text .=  "
		<$table>";
			foreach($row as $key => $val){
				if (!preg_match('#^\d+$#', $key, $match)){
					$text .=  "
					<$key>$val</$key>";
				}
			}
		$text .=  "
		</$table>";
	}

	$text .= "
	</table_$table>";
}
	$text .= "
</$db_name>";
echo $text;
mysql_close($connection);

When the file is executed, the file will generate an xml file. I will post how to import database from an xml file next time. Hope this simple post can help you alot.

http://septiadi.com/2011/05/20/export-mysql-into-xml/

Advertisements

One response to “Export MySql Into XML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: