Making XSL work for its money

Now that we can control how our output looks, based upon the XSL stylesheet its processed with, let's try something a little harder that will better demonstrate the flexibility of the XML/XSLT combination.

As mentioned previously, XSLT can transform your output into pretty much any format you want, including unformatted languages like SQL. If the xslt_test.php script is modified to check whether a certain HTTP GET variable is set, we can alter the format of the output merely by changing the URL.

This change needs to be implemented in two steps. Firstly, you need a new XSL stylesheet to transform your content into SQL. Naturally this will look a lot like the previous stylesheet, because the logic is basically the same: loop through all /channel/item elements, and output data about it.

Here is the XSL stylesheet necessary to transfer our example XML into SQL. Save this as sql.xsl in the same directory as the previous files.

<?xmlversion="1.0"encoding="utf-8"?> <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://my.netscape.com/rdf/simple/0.9/"
    >

    <xsl:output method="html" indent="no" encoding="utf-8" />

    <xsl:template match="/">
        <xsl:for-each select="/channel/item">
            INSERT INTO News (Title, Link) VALUES ('<xsl:value-of select="title"/>', '<xsl:value-of select="url"/>')<br />
        </xsl:for-each>
    </xsl:template>
    </xsl:stylesheet>

The key differences are that we no longer output any HTML. Our output target is different now, and HTML would not work in a MySQL query. Also, this time the stylesheet prints out the "url" value of the XML, along with the "title" value, nested inside an SQL query.

In order to facilitate the output selection, you also need to modify the xslt_test.php script so that it changes the input XSL files based upon the value of a variable. There are various ways to do this, but below I have included an example to get you started:

<?php
    $xsltproc = xslt_create();

    if (isset($USESQL)) {
        $xslinput = 'sql.xsl';
    } else {
        $xslinput='formatted.xsl';
    }

    $hResult=xslt_process($xsltproc,'final.rss',$xslinput);
    print$hResult;
    xslt_free($xsltproc)
?>

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: What else can XSL do? >>

Previous chapter: Handling the processed output

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.