Server-side XSLT transformations

If you need to transform XML with XSLT on the server, you could use MSXML on Microsoft platforms (ASP) or built-in XSL functions in PHP 5. The beauty of the PHP functions is that they provide the same API as the Firefox browser and the Sarissa library, so you don't have to reinvent the wheel.

I would often use XSLT on the server to separate data (XML) from its presentation. Its usage also results in cleaner server-side code, as the markup generation is separated from the programming logic. It's also extremely useful if you want to deploy XML/XSLT-based solution that has to support low-end clients (for example, search engine spiders).

Error handling Sarissa wrapper

In a previous post I've included a simple Sarissa wrapper that could be used to load an XML document (for example, XSLT stylesheet). If you want to perform more error checking and generate sensible errors, you could use these two functions:

  • loadFromServer function requests object load. If you provide a callback parameter, the load is asynchronous, otherwise it waits for the load to complete and return the wrapper object.
  • checkLoadStatus checks the various error conditions and throws appropriate errors.
var AWS = new Object();

AWS.loadFromServer = function (url,cb) {
var lso = new Object() ;

function loadHandler() {
if (lso.request.readyState == 4) cb(lso); }

lso.savedURL = url ;
lso.request = new XMLHttpRequest() ;
lso.request.open("GET", lso.savedURL, cb ? true,false);
if (cb) lso.request.onreadystatechange = loadHandler;
lso.request.send(null);

return lso;
}
AWS.checkLoadStatus = function (lso) {
var url = lso.savedURL ;
var xr = lso.request ;
var msg;

if (!url) throw("AWS.checkLoadStatus expects loadFromServer object") ;
if (xr.status != 200) throw (url + " failed: "+xr.statusText);
try {
var de = xr.responseXML.documentElement;
if (!de) msg = url + ": response is not a valid XML document";
} catch(err) {
msg = url + ": response is not a valid XML document (" + err + ")";
}
if (msg) throw(msg);
return xr.responseXML;
}