Current Location: Home> Latest Articles> PHP Tutorial: How to Interact with Database and Export Data as XML

PHP Tutorial: How to Interact with Database and Export Data as XML

M66 2025-06-07

Implementing Database Interaction and Storing Data as XML in PHP

In web development, interacting with databases is a fundamental and important operation. Exporting data from a database into XML format not only facilitates cross-platform data exchange but also simplifies subsequent data processing. This article explains how to connect to a database using PHP's mysqli extension, query data, and save the data as an XML file using the SimpleXMLElement class.

Establish Database Connection

First, we need to connect to the database using the mysqli extension. Here is an example:

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
<p>// Establish database connection<br>
$conn = new mysqli($servername, $username, $password, $dbname);</p>
<p>// Check connection success<br>
if ($conn->connect_error) {<br>
die("Connection failed: " . $conn->connect_error);<br>
}<br>

Execute SQL Query to Retrieve Data

After a successful connection, execute an SQL query to retrieve the required data. In this example, we get all records from the "users" table:

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

Convert Query Results to XML Format

Using PHP's SimpleXMLElement class, you can easily create an XML document. Example code:

$xml = new SimpleXMLElement('<users></users>');
<p>while ($row = $result->fetch_assoc()) {<br>
$user = $xml->addChild('user');<br>
$user->addChild('id', $row['id']);<br>
$user->addChild('name', $row['name']);<br>
$user->addChild('email', $row['email']);<br>
}<br>

Save XML File

Finally, save the XML data to a local file, for example, users.xml:

$xml->asXML('users.xml');

Summary

This article demonstrated how to use PHP's mysqli extension to connect to a database and query data, then use SimpleXMLElement to format and save the data as XML. This method facilitates cross-platform data transmission and integration. You can adjust the SQL statement and XML structure according to your needs or use PHP's DOMDocument class for more complex XML operations.