Home  >  Article  >  Database  >  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
Linda HamiltonOriginal
2024-11-08 04:28:01818browse

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();

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>

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!

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