04 May, 2010

XML formatted output of Database Schema using PHP

The following php code tends to be useful to export database schema as xml format.

Get Database Schema(table and fields names) as XML using PHP
<?php
$user = "root";
$passwd = "";
$host = "localhost";
$dbase = "testdb";

//connect to database
$conn = mysql_connect($host, $user, $passwd) or die("Could not connect");
//select the database
mysql_select_db($dbase);

//form the query
$tablesArr = array();
$resultQuery = "SHOW TABLES FROM ".$dbase;
$result = mysql_query($resultQuery);
while($res = mysql_fetch_row($result)) {
$tablesArr[] = $res[0];
}
mysql_free_result($result);
//generate xml formatted output
header("Content-Type: text/xml");
?>
<dbschema>
<?php foreach($tablesArr as $tables) { ?>
<table name="<?php echo $tables; ?>">
<?php
$fields = mysql_query("SHOW FIELDS FROM ".$tables);
while($field_res = mysql_fetch_row($fields)) {
?>
<field name="<?php echo htmlentities($field_res[0]); ?>" type="<?php echo htmlentities($field_res[1]); ?>" />
<?php
} //end of while
mysql_free_result($fields);
?>
</table>
<?php
} //end of foreach
?>
</dbschema>

No comments: