Home  >  Article  >  Database  >  How to Retrieve MySQL Database Output as XML in PHP?

How to Retrieve MySQL Database Output as XML in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 12:03:02612browse

How to Retrieve MySQL Database Output as XML in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn