php-mysqlHow to output XML from MySQL using PHP?
To output XML from MySQL using PHP, the following steps can be taken:
- Connect to the MySQL database using
mysqli_connect()
function.
$conn = mysqli_connect("localhost", "username", "password", "database");
- Execute a query to retrieve the data from the database using
mysqli_query()
function.
$result = mysqli_query($conn, "SELECT * FROM table");
- Create an XML document using
DOMDocument
class.
$doc = new DOMDocument();
- Create a root element and append it to the document using
createElement()
andappendChild()
methods.
$root = $doc->createElement("root");
$doc->appendChild($root);
- Iterate through the result set and create child elements for each row using
createElement()
andappendChild()
methods.
while ($row = mysqli_fetch_assoc($result)) {
$node = $doc->createElement("node");
$node->appendChild($doc->createElement("id", $row['id']));
$node->appendChild($doc->createElement("name", $row['name']));
$root->appendChild($node);
}
- Output the XML document using
saveXML()
method.
echo $doc->saveXML();
Output example
<?xml version="1.0"?>
<root>
<node>
<id>1</id>
<name>John</name>
</node>
<node>
<id>2</id>
<name>Jane</name>
</node>
</root>
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to call a stored procedure in MySQL using PHP?
- How to get a key-value array from a MySQL database using PHP?
- How to join tables with PHP and MySQL?
- How to use a MySQL union in PHP?
- How to generate a UUID in MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to create pagination in MySQL using PHP?
- How to fetch data from MySQL in PHP?
- How to escape a string for MySQL in PHP?
See more codes...