Query MySQL Database and Output XML via PHP
Problem:
Extract an XML output of specific columns ('udid' and 'country') from a MySQL database table using PHP.
Solution:
To achieve this, follow these steps:
PHP Code:
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>
The above is the detailed content of How to Output MySQL Data as XML Using PHP?. For more information, please follow other related articles on the PHP Chinese website!