Home > Database > Mysql Tutorial > How can I retrieve XML data from a MySQL database using PHP?

How can I retrieve XML data from a MySQL database using PHP?

Linda Hamilton
Release: 2024-11-08 04:28:01
Original
856 people have browsed it

How can I retrieve XML data from a MySQL database using PHP?

Extracting XML from MySQL Database Using PHP

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

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>
Copy after login

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!

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