Sunday, July 12, 2009

Create XML file with PHP 5 and MySQL

In this tutorial i would like to explain that how to create XML files in PHP 5 after extracting data from the MySQL database.

In this code there is no hard coded node for the XML files , The data is retrived from the database as an associative and transformed to the XML files.

Requirement

There should be DOM extension available in PHP installation.

Code Sample

Let's discuss how many step is here to write this code, there are three step to write the code

(i) Connection from MySQL databse.
(ii) Retrieve data from the database tables.
(iii) Write retrieved data in XML files.

Connection from MySQL databse

$con=mysql_connect('localhost' , 'testuser' , 'pass123');

if( $con)
{
echo "could not connect host 'localhost' . ";
exit();
}
if (!mysql_select_db('demo'))
{
echo "Cannot connect to database 'demo' . ";
exit();

Above script connect with database 'demo' and now we can fetch the data from this database tables.

Retrieve data from the database tables

$query = "SELECT * FROM tablename ";
$result = mysql_query ($query , $con);

Now we have a data amd need to write it in XML format.

Write retrieved data in XML files

Create new XML document

$document= new DOMDocument( '1.0' );

The first element we create in the XML document is known as the root element. Each XML document must have 1 root element.

Create root node


$root
node = $document->createElement('root');
$rootnode = $document->appendChild($rootnode );

Now after creating the root node we have to add the data from the database


while($row = mysql_fetch_assoc($result))
{
$node= $document->createElementNS( 'Item', 'ezobject:object-relation-list' );
$node = $rootnode->appendChild($node);

foreach ($row as $fieldname => $fieldvalue)
{
$child =
$document->createElement($fieldname);
$child =
$node ->appendChild($child);

$nodevalue = $document->createTextNode($fieldvalue);
$nodevalue = $child->appendChild($nodevalue);
}
}
$xml_doc = $document->saveXML();

echo $xml_doc;


The above tutorial help you to create XML file in PHP 5.

No comments: