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 create an SSL connection to MySQL using PHP?
- What port to connect to MySQL from PHP?
- How to replace a string in MySQL using PHP?
- How to use multiple prepared statements in PHP and MySQL?
- How to get the last insert ID in PHP MySQL?
- How to write an update query in MySQL using PHP?
- How to join tables with PHP and MySQL?
- How to get the first row of a result in MySQL using PHP?
- How to run multiple queries in PHP and MySQL?
See more codes...