Home > Database > Mysql Tutorial > How to Generate XML Output from a MySQL Database Using PHP?

How to Generate XML Output from a MySQL Database Using PHP?

Barbara Streisand
Release: 2024-11-11 10:44:03
Original
709 people have browsed it

How to Generate XML Output from a MySQL Database Using PHP?

Creating an XML Output from MySQL Database with PHP

Need to extract XML data from your MySQL database? Follow these steps using PHP to retrieve specific columns:

Step 1: Connect to Database

mysql_connect('server', 'user', 'pass');
mysql_select_db('database');
Copy after login

Step 2: Query Database

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

Step 3: Create XML Writer

$xml = new XMLWriter();
$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);
Copy after login

Step 4: Start XML Structure

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

Step 5: Loop Through Results

while ($row = mysql_fetch_assoc($res)) {
  $xml->startElement("country");
  $xml->writeAttribute('udid', $row['udid']);
  $xml->writeRaw($row['country']);
  $xml->endElement();
}
Copy after login

Step 6: End XML Structure

$xml->endElement();
Copy after login

Step 7: Set Output Header and Flush XML

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

Example Output:

<countries>
 <country udid="1">Country 1</country>
 <country udid="2">Country 2</country>
 ...
 <country udid="n">Country n</country>
</countries>
Copy after login

This code will generate an XML output containing the specified columns from the MySQL table. Customize the SQL query to retrieve different columns as needed.

The above is the detailed content of How to Generate XML Output from a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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