Xml file from database

We will collect the each records by using Mysql query and PDO. We will store all our output in string and then we can write to a file with .xml extension or print to webpage by using htmlspecialchars() function. You can read more on PHP & XML here.

Demo of the output in XML format

Here is the code.
require "config1.php"; // Connect to database

$sql="select *  from student"; 
$str ="<?xml version="1.0" encoding="UTF-8"?>n<student>";

foreach ($dbo->query($sql) as $row) {
$str .= "\n<details>\n\t\t\t<id>$row[id]</id>\n\t\t\t<name>$row[name]</name> ";
$str .= "\n\t\t\t <class>$row[class]</class>\n</details>"; } $str.= "\n</student>"; //$str=nl2br($str); //echo htmlspecialchars($str); // remove this line if you are writing to file echo $str; ///////////////////////////// /// Write to file //////////// /* $file_name="test_file.xml"; // file name $fp = fopen ($file_name, "w"); // Open the file in write mode, if file does not exist then it will be created. fwrite ($fp,$str); // entering data to the file fclose ($fp); // closing the file pointer chmod($file_name,0777); */ ?>
Using MySQLi database connection and SimpleXMLElement to addChild()
header('Content-Type: text/xml');
require "config.php"; // database connection file

$e = new SimpleXMLElement('<detils/>');
if($stmt = $connection->query("SELECT id, name ,class, mark FROM student")){

while ($row = $stmt->fetch_assoc()) {
	//echo $row['id'],$row['name'],$row['class'].$row['mark']."<br>";
	$add=$e->addChild('id', $row[id]);
	$add=$e->addChild('name', $row[name]);
	$add=$e->addChild('mark', $row[mark]);
echo $connection->error;
echo $e->asXML(); 

Read more on MySQLi SELECT query to get Data from table

Read more on displaying records
Download the student table here


* indicates required
Subscribe to plus2net


    Post your comments , suggestion , error , requirements etc here .

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer