Firehed's Blog

MySQL Query Results to XML in PHP

"XML is like violence - if it's not working, you're not using enough" - stupid internet meme

But it's sort of true.  PHP5's SimpleXML extension makes it a whole lot easier to deal with, both for creating the stuff and for freaks like me that don't want to dabble with XSLT.  In any case, I wanted a simple way to throw XML around, both so I can create an API fairly easily in the future and not have to screw around with DB query result objects.  I didn't find any great approaches pre-built, so I went ahead and made my own. So here:

function mysql_to_xml($mysql_result, $root_node_name, $child_node_name) {
$xml = new SimpleXMLElement('< ?xml version="1.0" encoding="UTF-8"?>< ' . $root_node_name . '>');
	while ($row = mysql_fetch_assoc($mysql_result)) {
$newrow = $xml->addChild($child_node_name);
foreach ($row as $key => $value ) {
$newrow->addChild($key, $value);
}
}
	return $xml;
}

Updated... Wordpress really made a mess of the first one, and I did an even worse job fixing it.

function mysql_to_xml($mysql_result, $root_node_name = 'result', $child_node_name = 'row') {
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><' . $root_node_name . '></' . $root_node_name . '>');

while ($row = mysql_fetch_assoc($mysql_result)) {
$newrow = $xml->addChild($child_node_name);
foreach ($row as $key => $value ) {
$newrow->addChild($key, $value);
}
}
return $xml;
}

In my SQL functions, I'm able to return an XML object quite easily:

return mysql_to_xml(mysql_query($query), 'response', 'content');

And to get it in the first place:

$sql = new SQL_as_XML;
 $xml = $sql->get_content_by_permalink($permalink, $page);

(the SQL_as_XML class is a series of functions that build and run a query, then return the XML using the previous snippet)

Finally, if you want to output the raw XML (after perhaps finagling it into an RSS feed):

echo $xml->asXML();

Questions? Ask. Improvements? Tell. And yes, I already know that I really should set default values for $root_node_name and $child_node_name in the original function. I'll get there.

And yes, you'll have to excuse the blog making a mess of the formatting. :(