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

How to Retrieve MySQL Database Output as XML in PHP?

Susan Sarandon
Release: 2024-11-08 12:03:02
Original
661 people have browsed it

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');
Copy after login

Next, execute an SQL query to fetch the desired columns:

$sql = "SELECT udid, country FROM table ORDER BY udid";
$res = mysql_query($sql);
Copy after login

To generate the XML output, instantiate an XMLWriter object:

$xml = new XMLWriter();
Copy after login

Configure the XMLWriter and start the document:

$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('countries');
Copy after login

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();
}
Copy after login

End the XML elements and document:

$xml->endElement();
$xml->endDocument();
Copy after login

Finally, set the appropriate HTTP header and output the XML:

header('Content-type: text/xml');
$xml->flush();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template