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
Barbara StreisandOriginal
2024-11-11 10:44:03641browse

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

Step 2: Query Database

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

Step 3: Create XML Writer

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

Step 4: Start XML Structure

$xml->startElement('countries');

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

Step 6: End XML Structure

$xml->endElement();

Step 7: Set Output Header and Flush XML

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

Example Output:

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

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:
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