To retrieve an XML output of specific database columns using PHP, utilize XMLWriter as exemplified below:
// Connect to MySQL mysql_connect('server', 'user', 'pass'); mysql_select_db('database'); // Query the database $sql = "SELECT udid, country FROM table ORDER BY udid"; $res = mysql_query($sql); // Initialize XMLWriter $xml = new XMLWriter(); // Configure XML output $xml->openURI("php://output"); $xml->startDocument(); $xml->setIndent(true); // Create root element $xml->startElement('countries'); // Loop through query results while ($row = mysql_fetch_assoc($res)) { // Start country element $xml->startElement("country"); // Add attributes $xml->writeAttribute('udid', $row['udid']); // Output country $xml->writeRaw($row['country']); // End country element $xml->endElement(); } // End root element $xml->endElement(); // Set output headers header('Content-type: text/xml'); // Flush and output XML $xml->flush();
Sample XML 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>
The above is the detailed content of How can I retrieve XML data from a MySQL database using PHP?. For more information, please follow other related articles on the PHP Chinese website!