RSS
 

Creating XML in PHP

28 Jul

Quite often I need to create some XML via PHP, pulling data from a MySQL database.

I have tried various methods but I always come back to this. I like the way that I get full control over doing it explicitly, so thought I would share the code. I am using the MySQL PHP class from Ricocheting.

There are loads of examples out there already on the web, but I hope the code below is very easy to understand as it uses simple PHP code.

<?php
 
//pick up required variables
$userName = $_GET['username'];
$password = $_GET['password'];
 
//include the required files
require_once('config.php');
require_once("Database.class.php");
 
// create the $db ojbect
$db = new Database($config['server'], 
	$config['user'], 
	$config['pass'], 
	$config['database'], 
	$config['tablePrefix']);
 
// connect to the server
$db->connect();
 
//build the query
$query = "SELECT * FROM ".$db->pre."useraccount "; 
 
//build the where statements
$where = "WHERE (userAccountId > 0)";
 
if ($userName) {
	$where = " AND (userName = '" . $db->escape($userName). "')";
}
 
if ($password) {
	$where = " AND (password = '" . $db->escape($password). "')";
}
 
//get the FULL record count
$sql2 = "SELECT count(0) AS theCount FROM ".$db->pre."useraccount $where";
 
$countRecRows = $db->query($sql2);
while ($countRecRow = $db->fetch_array($countRecRows)) {
	$recordCount = $countRecRow['theCount'];
}
 
//execute the main query
$countRows = $db->query($query . $where);
 
//set up the php headers so that the page doesnt cache etc
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/xml");
 
//include the page header info
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
 
//begin the xml data
echo "<useraccounts>\n";
 
//set up the result info
echo  "<total>$recordCount</total>\n";
 
//loop through all the records
while ($row = $db->fetch_array($countRows)) { 
	echo "<useraccount id=\"".$row['userAccountId'] ."\">\n";
 
	echo "<username>";
	echo $row['userName'];
	echo "</username>\n";
 
	echo "<fullname>";
	echo $row['fullName'];
	echo "</fullname>\n";
 
	echo "<accesscode><![CDATA[";
	echo $row['accessCode'];
	echo "]]></accesscode>\n";
 
	echo "</useraccount>\n";
}
 
echo "</useraccounts>";
 
//free the result
$db->close();
?>
 
 

Tags: , , ,

Leave a Reply

 

 
  1. GET DOWN TONIGHT » Using XML in your jQuery to populate input boxes

    August 11, 2009 at 7:07 pm

    [...] a previous post I wrote about creating XML pages with MySQL data, using PHP. In this article, I’ll explain in [...]