Monday, August 13, 2012

Generate XML from MySQL database via PHP

<?php

mysql_connect('localhost', 'root', 'admin');
mysql_select_db('xml');

$sql = "SELECT udid, country,code FROM country ORDER BY udid";
$res = mysql_query($sql);

$xml = new XMLWriter();

$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('countries');

while ($row = mysql_fetch_assoc($res)) {


   $xml->startElement("udid");
   $xml->writeRaw($row['udid']);
   $xml->endElement();
 
 
   $xml->startElement("country");
   $xml->writeAttribute('udid', $row['udid']);
   $xml->writeRaw($row['country']);
   $xml->endElement();
 
  $xml->startElement("code");
  $xml->writeRaw($row['code']);
  $xml->endElement();
 
}

$xml->endElement();

header('Content-type: text/xml');
$xml->flush();

?>

7 comments:

  1. Working Perfectly.But Instead of showing XML in browser I wanted to save this XML output as XML file.Also if any attributes are empty it should not be shown.Kindly give
    idea/tips.


    Aston Martin DB9
    450
    2004

    Bugatti Veyron EB 16.4
    1001
    2006

    Koenigsegg CCX
    806
    2006

    Lamborghini Murcielago LP640
    633
    2006

    Pagani Zonda C12 F
    602
    2005

    ReplyDelete
    Replies
    1. Simply do fwrite like below

      $my_file = 'file.xml';
      $handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
      $data = 'New data line 1';
      fwrite($handle, $data);
      $new_data = "\n".'New data line 2';
      fwrite($handle, $new_data);

      Delete
    2. or instead of:
      $xml->openURI("php://output");
      use this:
      $xml->openURI("test.xml");
      it will be saved in the same folder where your php file is.

      Delete
  2. Hi, I received the error below. Can you explain to me? Many thanks.

    This page contains the following errors:

    error on line 2 at column 1: Extra content at the end of the document
    Below is a rendering of the page up to the first error.

    ReplyDelete
  3. Hi,
    I am not able to duplicate the issue with this code. please tell me how you do it?

    ReplyDelete
  4. Thanks for the article mate.
    Its really helpful.
    http://www.techrecite.com

    ReplyDelete