How to get xml data from MySQL database using JQuery, Ajax and PHP
Let say we have this data in MySql database:
Id Name Age
0 Tom 12
1 Jerry 13
2 Donald 14
We want to call this data using ajax, retrieve the data as xml and convert it to array and object.
First, inside your html file for example index.html or any page you want to call that data, put the Javascript code as shown below:
var param = new Object();
var dataList = new Array();
var http = new XMLHttpRequest();
var url = "http://localhost/path to your file/get_data_xml.php";
param['id'] = '1';
var params = "param="+ JSON.stringify(param); $.ajax({'async':'true','url':url,'data':params,'type':'POST','dataType':"xml"}).done(function(result) {
var xml = result;
var xmlData = xml.getElementsByTagName("xmlData")[0];
var index = xmlData.getElementsByTagName("index");
for(i=0;i
After that create a php file to generate the xml data and named it as get_data_xml.php. Put the PHP code as shown below:
require('../path to your file/cls_generateXml.php');
header('Content-type: text/xml');
$param = json_decode(str_replace('\\','',$_POST['param']));
$dataList = doGetData($param);
try {
/*** a new dom object ***/
$dom = new domDocument;
/*** make the output tidy ***/
$dom--->formatOutput = true;
/*** create the root element ***/
$dom->appendChild($dom->createElement( "xmlData" ));
/*** create the simple xml element ***/
$sxe = simplexml_import_dom( $dom );
if(!empty($dataList)) {
foreach($dataList as $key => $value) {
$index = $sxe->addChild("index");
$index->userId = $value['id'];
}
}
/*** show the xml ***/
echo $sxe->asXML();
}
catch( Exception $e ) { echo $e->getMessage(); }
function doGetData($param) {
$obj = new cls_generateXml();
$dataList = $obj->getData($param);
return $dataList;
}
Create another php file and named it as cls_generateXml.php. This file is used to get data from database.
class cls_generateXml {
public function dbConnect() {
host = 'your host name';
user = 'username';
password = 'password';
dbName = 'database name';
$link = mysqli_connect(host, user, password, dbName); mysqli_select_db($link,dbName); mb_language('uni');
mb_internal_encoding('UTF-8');
mysqli_query( $link,"SET character_set_results=utf8");
mysqli_query( $link,"SET character_set_server=utf8");
mysqli_query( $link,"SET character_set_database=utf8");
mysqli_query( $link,"set names 'utf8'"); return $link;
}
public function getData(param) {
$con = $this->dbConnect();
$sql = " SELECT * FROM tbl_data WHERE id = '".param['id']."' ";
$query = mysqli_query($con,$sql);
if (!$query) { die(mysqli_error($con)); }
while($result = mysqli_fetch_assoc($query)) {
$dataList[] = $result;
}
mysqli_close($con);
return $dataList;
}
}