Get MySQL database output via PHP to XML Get MySQL database output via PHP to XML xml xml

Get MySQL database output via PHP to XML


An example with XMLWriter.

mysql_connect('server', 'user', 'pass');mysql_select_db('database');$sql = "SELECT udid, country FROM table 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("country");  $xml->writeAttribute('udid', $row['udid']);  $xml->writeRaw($row['country']);  $xml->endElement();}$xml->endElement();header('Content-type: text/xml');$xml->flush();

Output:

<?xml version="1.0"?><countries> <country udid="1">Country 1</country> <country udid="2">Country 2</country> ... <country udid="n">Country n</country></countries>


<?phpmysql_connect('myserver', 'username', 'password');mysql_select_db('mydatabase');$result = mysql_query('SELECT `udid`, `country` FROM `MyTable`');while($data = mysql_fetch_assoc($result)) {  foreach($data as $key => $value) {    echo "<$key>$value</$key>";  }}?>

This code snippet should give you a good start. But without the wanted XML structure, it's hard to do better.

However I'm not sure PHP is the right solution for this task. Many tools, like phpmyadmin for example, can output mysql data in XML format.


<?phpmysql_connect('myserver', 'username', 'password');mysql_select_db('mydatabase');$result = mysql_query('SELECT `udid`, `country` FROM `MyTable`');$Result = "<?xml version='1.0' encoding='utf-8'?>\n<employees>\n";while($data = mysql_fetch_assoc($Recordset1)) {  $Result .= " <employee>\n";  foreach($data as $key => $value) {    $Result .=  "  <$key>$value</$key>\n";  }    $Result .= " </employee>\n";}$Result .= "</employees>\n";echo $Result;?>