Tuesday, 24 July 2012

Create Mysqldata to xml using php


Hi friends, I have code for how to create a xmll file with mysql data using php code.
Follow the below steps to retrieve the data from database to xmlfile

Config.php
<?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");
?>


Xmlcreate.php

<?php
                include("config.php");
                $query = "SELECT * FROM product";
                $result = mysql_query($query);
                $file= fopen("results.xml", "w");
                $_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
                $_xml .= "<table>\n";
                while ($row = mysql_fetch_array($result)) {
                if ($row[1]) {
                $_xml .="\t<id title=\"".$row[0]."\">";
                $_xml .="\t<name>".$row[1]."</name>";
                $_xml .="\t<q>".$row[2]."</q>";
                $_xml .="\t<price>".$row[3]."</price>";
                $_xml .="\t</id>\n";
                } else {
                $_xml .="\t<id title=\"Nothing Returned\">";
                $_xml .="\t<file>none</file>";
                $_xml .="\t</id>";
                } }
                $_xml .="</table>";
                fwrite($file, $_xml);
                fclose($file);
echo "XML has been written.<a href=\"result.php\">View the XML.</a>";
?>

Result.php

<?php
        include("config.php");
        $xml = simplexml_load_file("results.xml");
                echo $xml->asXML();
?>

1 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More