Firehed's Blog

Applying XSLT to XML in PHP using SimpleXML

Since I'm now going crazy with the use of XML all over the place, I figured it's better to work with XSLT rather than bizarre loops within PHP - because of both portability and manageability (I don't expect to change platforms but having a relatively simple way to do so is a plus, and storing everything in an external file should also simplify things).

So another simple function here, as I've found XSLT to be rather convoluted in PHP5 and would quite like to simplify its use.  As usual, my tabbing will probably go straight to hell.

function apply_xslt($simplexml, $path_to_xslt) {
    $xslt_file = new DOMDocument;
    $xslt_file->load($path_to_xslt);

    $xml = new DOMDocument;
    $xml->loadXML($simplexml->asXML());

    $transform = new XSLTProcessor();
    $transform->importStyleSheet($xslt_file);

    return $transform->transformToXML($xml);
}

Now all you have to do is pass the function a SimpleXML object (see my post on XMLifying DB results) and get on with your life.

$db_results = new SQL_as_XML;
echo apply_xslt($db_results->get_list_of_content_by_author_permalink('eric-stern','1'), 'some_stylesheet.xslt');

And just for reference on the SQL_as_XML class:

class SQL_as_XML {

function get_content_by_permalink($content_permalink, $page = 0) {
$content_permalink = clean($content_permalink);//sanitize input

if (!is_numeric($page)) {
$page = 1; //$page also sanitized }

$query = "SELECT content.publish_date,
content.last_edit_date,
content.title,
content.number_of_pages,
content.permalink AS content_permalink,
authors.display_name,
authors.permalink AS author_permalink,
content_pages.body
FROM content
JOIN authors ON content.author_id = authors.id
JOIN content_pages ON content_pages.content_id = content.id
WHERE content.permalink = '$content_permalink'
AND content_pages.page_number = $page";

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

//other functions structured similarly
}

So there you go.