Formatting Control with XSL

calendar October 11, 2009

Amazon provides an interesting service to its corporate customers.The customer can skin an Amazon page by providing an XSL stylesheet that formats the XML data about the products,prices and related data.This means that if you are a corporate customer, you can add your own links and graphs and even customize the look of Amazon.com.

The scripts below do the same with PHP’s XSL engine.The processor takes two inputs, the input.xml file contains the data for the page, and the format.xsl file contains the formatting for the page.

Output from XML and XSL:

<?php
 $xml = new DOMDocument();
 $xml->Load("input.xml");
 $xsl = new DOMDocument();
 $xsl->Load("format.xsl");
 $xslproc = new XSLTProcessor();
 $xslproc->importStylesheet($xsl);
 print $xslproc->transformToXML($xml);
 ?>
Save the code as output.php.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
 <books>
 <book name="book1" />
 <book name="book2" />
 <book name="book3" />
 </books>
Save the code as input.xml.
XSL  to handle formatting:
<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:output method="html" />
 <xsl:template match="/">
 <html>
 <body>
 <xsl:for-each select="/books/book">
 <xsl:value-of select="@name" />
 </xsl:for-each>
 </body>
 </html>
 </xsl:template>
 </xsl:stylesheet>

Save the code as format.xsl.

Execute output.php from the command line:

% php output.php

admin

Leave a Reply

You must be logged in to post a comment.