Retrieve data from MySQL table and generate XML in PHP

     Hi, guys. Today I am going to explain about retrieve data from a MySQL table and show them in a PHP web page but in XML format.

     After you see the following image, you will be understand what I am going to do today. This is the final out put I am expecting from todays’ lesson.

XML content in a PHP page
Figure 1

     Today also I am using the database.php file and constant.php file that I have used in one of my earliest post. So the following is the content which generate the above page.


function parseToXML($htmlStr) 
// String replace content goes here
return $xmlStr; 

// Select all the rows in the member_details table
$query = "SELECT * FROM `member_details`";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());

// To see the db errors and php errors, comment the following line
header("Content-type: text/xml");

// Start XML file, echo parent node
echo '**anuja>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  echo '**anuj ';
  echo 'ID="' . parseToXML($row['id']) . '" ';
  echo 'NIC="' . parseToXML($row['nic']) . '" ';
  echo 'Name="' . $row['name'] . '" ';
  echo 'Age="' . $row['age'] . '" ';
  echo '/>';

// End XML file
echo '**/anuja>';

     First of all you have to fill the missing parts of the above code sample. I had to eliminate some code parts because of the formatting problem giving by the WordPress blog.

     Replace ** with < bracket. The relevant code phase for “// String replace content goes here” is;

return $xmlStr;

     So let me tell you where these kinds of work practically used in developing. I met this code while I was developing Google map component. So the credit goes to the Google and thank you Google for guiding us good code practice rather that download a component and plug it in to our existing systems.

That’s it for today 🙂 Bye…


About AnujAroshA

Working as a Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in PHP examples. Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s