9951 explained code solutions for 126 technologies


php-mysqlHow to output XML from MySQL using PHP?


To output XML from MySQL using PHP, the following steps can be taken:

  1. Connect to the MySQL database using mysqli_connect() function.
$conn = mysqli_connect("localhost", "username", "password", "database");
  1. Execute a query to retrieve the data from the database using mysqli_query() function.
$result = mysqli_query($conn, "SELECT * FROM table");
  1. Create an XML document using DOMDocument class.
$doc = new DOMDocument();
  1. Create a root element and append it to the document using createElement() and appendChild() methods.
$root = $doc->createElement("root");
$doc->appendChild($root);
  1. Iterate through the result set and create child elements for each row using createElement() and appendChild() 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);
}
  1. 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

Edit this code on GitHub