Showing posts with label PHP with XML. Show all posts
Showing posts with label PHP with XML. Show all posts

Wednesday, February 22, 2012

Create XML file using MySql Data


This program is for create XML file using data taken from Mysql server. The .XML file will create in your D drive. You may change location according to your system setting and also don’t forget to change database name and table name of program.



Step 1) Copy and paste below code to create .XML file from MySql Database.
<?php
$conn=mysql_connect("localhost","root","");
if($conn==NULL)
  echo "Connection loss";
$db=mysql_select_db("ajax",$conn);
if($db==NULL)
  echo "Connection loss";
$qur="select * from stud";
$ans=mysql_query($qur);
$output.= "<root>";
while($row=mysql_fetch_array($ans))
{
  $output.="<person>";
  $output.="<name>".$row['name']."</name>";
  $output.="<surname>".$row['surname']."</surname>";
  $output.="<roll>".$row['roll']."</roll>";
  $output.="</person>";
} 
$output.="</root>";

$file_name = "D:\\myxml.xml";
$file_pointer = fopen($file_name, "w+");
fwrite($file_pointer, "$output");
fclose($file_pointer);
print "data written to file successfully"; 
?>

Read XML data using PHP


Read XML data using PHP
This program will parse XML data using PHP. Create a XML file and load the XML file into your PHP program. This program will extract data from XML file



Step 1 )Create xyx.xml file using below code. And save in same location with your PHP file.

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/css" href="pqr.css"?>
<person>
   <name>Sourav</name>
   <surname>Kayal</surname>
</person>  

Step 2) Create a PHP file using below code. And run it. It will display the XML file data.

<?php
$doc = new DOMDocument();
$doc->load('xyx.xml');

$employees = $doc->getElementsByTagName( "person" );
foreach( $employees as $employee )
{
$names = $employee->getElementsByTagName("name");
$name = $names->item(0)->nodeValue;

$ages= $employee->getElementsByTagName("surname");
$age= $ages->item(0)->nodeValue;

echo "<b>$name - $age \n</b><br>";
}
?>