Retrieving MySQL Database Output as XML in PHP
To retrieve XML output from a MySQL database containing specific columns, follow these steps using PHP:
First, establish a connection to the database:
mysql_connect('server', 'user', 'pass'); mysql_select_db('database');
Next, execute an SQL query to fetch the desired columns:
$sql = "SELECT udid, country FROM table ORDER BY udid"; $res = mysql_query($sql);
To generate the XML output, instantiate an XMLWriter object:
$xml = new XMLWriter();
Configure the XMLWriter and start the document:
$xml->openURI("php://output"); $xml->startDocument(); $xml->setIndent(true); $xml->startElement('countries');
Loop through the query results and generate XML elements for each row:
while ($row = mysql_fetch_assoc($res)) { $xml->startElement("country"); $xml->writeAttribute('udid', $row['udid']); $xml->writeRaw($row['country']); $xml->endElement(); }
End the XML elements and document:
$xml->endElement(); $xml->endDocument();
Finally, set the appropriate HTTP header and output the XML:
header('Content-type: text/xml'); $xml->flush();
This process will generate an XML document containing the specified columns from your MySQL database.
The above is the detailed content of How to Retrieve MySQL Database Output as XML in PHP?. For more information, please follow other related articles on the PHP Chinese website!