Monday, January 28, 2008

sql2xml

OK, here we go :)

I will try to show you my solution to extract XML from MySQL database.

Function sql2xml accept SQL and transform it to XML. With this function, you also have ability to "explain" hierarchy how your data will be organized.

This code is a small (but most important) part of our custom made framework.

Functions and PHP code are well documented so if you know a little of PHP you could understand the algorithm and what is going on ...

Here goes sql2xml.php code ...


<?
// execute SQL statement (structure, skip & display have default values)
// sql - sql statement
// structure - in a form of string like "4,3,3, ..." and means first level has
// first 4 columns, then second have next 3 columns and so on
// (last level shouldn't be descripted in $structure)
// skip - number of rows which will be skiped (suitable for paging)
// display - number of rows to display (suitable for paging)

function sql2xml_mysql($sql, $structure=0, $skip=0, $display=9999){

// setting proccess row function (which will process every row)
$process_row = getProcessRow();

// test sql variable (if sql variable doesn't exist, return)
if (!$sql) return;

// make connection to database
$db_cn = db_connect_mysql();

// execute query
$result = mysql_query($sql, $db_cn);

// test connection
if ($result == NULL){
trigger_error(mysql_errno() . ": " . mysql_error() . "\n");
$result = -1;
}

// count column number
$ncols = mysql_num_fields($result);

// test for (hierarchy) structure
if ($structure == 0) {$deep = -1; $pos = 0;}
else{
$hierarchy = explode(',', $structure); // hierarchy levels
$deep = count($hierarchy); // number of levels
// set flags for opened tags
for ($i=0; $i < $deep; $i++) $tagOpened[$i] = false;
// set initial row to some strange & different value
for ($i=0; $i < $ncols; $i++) $rowPrev[$i] = microtime();
}

// loop through result set
while($row = mysql_fetch_row($result)){
// loop through hierarchy levels (dataset columns)
for ($level=0,$pos = 0; $level<$deep; $level++){
// prepare row segments to compare
for ($i=$pos; $i < $pos+$hierarchy[$level]; $i++){
$row_current .= trim($row[$i]);
$row_previous .= trim($rowPrev[$i]);
}
// test row segments between row_current and row_previous
if ($row_current != $row_previous){
// close that tag and all tags bellow
for ($i=$deep; $i>=$level; $i--){
if ($tagOpened[$i]) print "\n";
$tagOpened[$i] = false;
}
// reset the rest of rowPrev
for ($i=$pos; $i< $ncols; $i++) $rowPrev[$i] = microtime();
// set flag to opened
$tagOpened[$level] = true;
print "\n";
// loop through hierarchy level
for ($i=$pos; $i < $pos+$hierarchy[$level]; $i++){
$name = strtoupper(mysql_field_name($result, $i));
print "<$name>" . $process_row($row[$i], $i) . "\n";
}
}
// increment row position
$pos+=$hierarchy[$level];
// reset row segments (part of columns)
$row_current = '';
$row_previous = '';
}
// print the rest
print "\n";
for ($i=$pos; $i < $ncols; $i++){
$name = strtoupper(mysql_field_name($result, $i));
print "<$name>" . $process_row($row[$i], $i) . "\n";
}
print "
\n";
$rowPrev = $row; // remember previous row
}
// close opened tags
for ($level=$deep; $level>=0; $level--) if($tagOpened[$level]) print "
\n";
// return number of selected rows
return mysql_num_rows($result);
}

//
// functions needed for sql2xml function
//


// return database connection
function db_connect_mysql(
$db = 'test',
$host = 'localhost',
$username = 'your_username',
$password ='your_password'){
// create connection
$db_cn = mysql_pconnect($host, $username, $password);
// set database
mysql_select_db($db, $db_cn);
// return database connection
return $db_cn;
}

// default convert function
// trim, and convert special chars that comes from database
// second parameter is column number (not needed here, but maybe
// in some custom convert function)

function convert($str, $column=0){
// convert &, <, >, ' -> &, < ...
$str = htmlspecialchars($str);
// return trimed string
return trim($str);
}

// get proces row function
function getProcessRow(){
global $_process_row;
if ($_process_row == NULL) return 'convert';
else return $_process_row;
}

?>

<DOCUMENT?>
<!-- example of how to use function sql2xml -->
<? sql2xml_mysql('SELECT a.alb_id, a.alb_name,
s.sng_number, s.sng_name
FROM album a, song s
WHERE a.alb_id = s.alb_id
ORDER BY a.alb_id, s.sng_number', '2') ?>
</DOCUMENT?>


You also need MySQL database, and here is mysqldump for your database "test":


CREATE TABLE `album` (
`alb_id` int(11) NOT NULL auto_increment,
`alb_name` varchar(20) NOT NULL,
PRIMARY KEY (`alb_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

INSERT INTO `album` VALUES
(1,'Nevermind'),
(2,'Band of Gypsys');

CREATE TABLE `song` (
`sng_id` int(11) NOT NULL auto_increment,
`alb_id` int(11) NOT NULL,
`sng_number` int(11) NOT NULL,
`sng_name` varchar(40) NOT NULL,
PRIMARY KEY (`sng_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;

INSERT INTO `song` VALUES
(1,1,1,'Breed'),
(2,1,2,'Come As You Are'),
(3,1,3,'Drain You'),
(4,1,4,'Endless, Nameless'),
(5,1,5,'In Bloom Lyrics'),
(6,1,6,'Lithium'),
(7,1,7,'Lounge Act'),
(8,1,8,'On A Plain'),
(9,1,9,'Polly'),
(10,1,10,'Smells Like Teen Spirit'),
(11,1,11,'Something In The Way'),
(12,1,12,'Stay Away'),
(13,1,13,'Territorial Pissings'),
(14,2,1,'WHO KNOWS'),
(15,2,2,'MACHINE GUN'),
(16,2,3,'CHANGES'),
(17,2,4,'POWER TO LOVE'),
(18,2,5,'MESSAGE TO LOVE'),
(19,2,6,'WE GOTTA LIVE TOGETHER');



Happy PHP. MySQL & XML programming :)

No comments: