Open In App

How to generate an XML file dynamically using PHP?

A file can be generated using PHP from the database, and it can be done by the static or dynamic method in PHP. Static methods can be called directly – without creating an instance of a class. Here we are going to discuss how to create an XML file dynamically.
 

$result=mysqli_query($con, "Select * from Table_name"); 
$xml = new DOMDocument("1.0");
$fitness=$xml->createElement("users");
echo "".$xml->saveXML()."";

The next thing we need to do is fetch the elements from the table. 
Example: If a table has two elements then it should create two XML elements. For that, we will simply use a while loop inside which there will be mysql_fetch_array function to fetch all the data from the table.
Since the database is connected to a local server it won’t run in your ide but once you have made the database it will work fine. To create the database follow the below mentioned procedure 
 



Program: 




<?php
$con=mysqli_connect("localhost", "root", "", "fitness");
 
if(!$con){
    echo "DB not Connected...";
}
else{
$result=mysqli_query($con, "Select * from users");
if($result>0){
$xml = new DOMDocument("1.0");
 
// It will format the output in xml format otherwise
// the output will be in a single row
$xml->formatOutput=true;
$fitness=$xml->createElement("users");
$xml->appendChild($fitness);
while($row=mysqli_fetch_array($result)){
    $user=$xml->createElement("user");
    $fitness->appendChild($user);
     
    $uid=$xml->createElement("uid", $row['uid']);
    $user->appendChild($uid);
     
    $uname=$xml->createElement("uname", $row['uname']);
    $user->appendChild($uname);
     
    $email=$xml->createElement("email", $row['email']);
    $user->appendChild($email);
     
    $password=$xml->createElement("password", $row['password']);
    $user->appendChild($password);
     
    $description=$xml->createElement("description", $row['description']);
    $user->appendChild($description);
     
    $role=$xml->createElement("role", $row['role']);
    $user->appendChild($role);
     
    $pic=$xml->createElement("pic", $row['pic']);
    $user->appendChild($pic);
     
}
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("report.xml");
}
else{
    echo "error";
}
}
?>

Output: 
 



 


Article Tags :