SlideShare a Scribd company logo
Introduction to XSLT with PHP4 PHPCon 2002 10/25/2002, Millbrae California USA Stephan Schmidt
Table of Contents About the speaker Structuring content XML basics Introduction to XSLT Using PHP‘s XSLT functions Advanced XSLT Drawbacks of XSLT Transforming XML without XSLT patXMLRenderer Similar applications
Stephan Schmidt Web application developer since 1999 Working for Metrix Internet Design GmbH in Germany Maintainer of  www.php-tools.net Author of patTemplate, patXMLRenderer, patUser and others Focussing on the combination of XML and PHP and the separation of content and layout
Separation of content and layout Why? Modify layout without accessing content Modify content without accessing layout Different views for different devices (Browser, mobile phone,…) Different views for different user types (visitor, client, administrator) How? Different approaches…
Structuring content Classic websites and the use of HTML: » no structure at all » not readable by machines Classic software-development uses RDBMs: » hardly readable by humans Use of relations to implement structure Use of several table (normalization) Use of cryptic IDs
Using XML for structured data Readable by humans: » complete data in one file » self-explaining tag names » self-explaining attribute names » structured by indentation Readable by machines: » Well-formed document » only ASCII data » Validation with DTD or schema Separation of content and layout
Building a content structure 1 Split content into logical elements navigation Sections and parargraphs Lists and list elements Tags should describe their content, e.g. use <important> for important parts in you page No layout-elements like <br>, use <p>...</p> instead Define and write down page structure XML Schema DTD
Building a content structure 2
Building a content structure 3
Building a content structure 4
Basic XML Rules Each document needs a root element Each tag has to be closed, i.e. <p>…</p> instead of just <p> Use trailing slash to indicate an empty element (<br/> instead of <br>) Elements may not overlap (<p>…<b>…</b>…</p> instead of <p>…<b>…</p>…</b>) Attribute values have to be enclosed in double quotes Entities for <, >, &, “ and ‘ have to be used
XML Example <page> <headline> Introduction to XSLT </headline> <section title=&quot;Abstract&quot;> <para> The presentation includes </para> <list> <listelement> Examples </listelement> <listelement> Some PHP code </listelement> </list> </section> <section title=&quot;About the author&quot;> <para> Web developer from Germany </para> </section> </page>
Tree view of a document Each piece of information in an XML document is referred  to as a node: Element Nodes (tags) Attribute Nodes (attributes of a tag) Text Nodes (text and Cdata sections) Comment Nodes (<!-- ... -->) Processing Instruction Nodes (<?PHP ... ?>) Namespace Nodes (xmlns:myns=“...“)
Tree view of a document (example)
XML Transformations Each tag has to be transformed into an HTML representation: <headline> Introduction to XSLT </headline> … is transformed to: <font size=&quot;+1&quot;> <br><b> Introduction to XSLT </b><br><br> </font>
Introduction to XSLT Stylesheet must be an XML document (well-formed and valid) Based on pattern-matching („When you see something that looks like this, do something else“) Free of sideeffects (One rule may not influence or modify others) Use of iteration and recursion
„ Hello World“ Example (XML) Sample Document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting> Hello World! </greeting> </greetings>
„ Hello World“ Example (XSL) <xsl:stylesheet xmlns:xsl= &quot;http://www.w3.org/1999/XSL/Transform&quot;  version= &quot;1.0&quot; > <xsl:output method= &quot;html&quot; /> <xsl:template match= &quot;/&quot; > <html> <body> <xsl:apply-templates select= &quot;greetings/greeting&quot; /> </body> </html> </xsl:template> <xsl:template match= &quot;greeting&quot; > <h1> <xsl:value-of select= &quot;.&quot; /> </h1> </xsl:template> </xsl:stylesheet>
„ Hello World“ Example (Output)
Closer look at the XSL template <xsl:stylesheet>  root element and its attributes are mandatory <xsl:output/>  defines output format (sets some properties in the XSLT processor ) Two  <xsl:template>  tags define how XML elements are transformed <xsl:apply-templates>  invokes other templates
Transformation Workflow Read stylesheet, so that each part may be easily accessed Read the XML document and build tree view of the document Transform the document Check for nodes to process („the context“) Get the next node from the context Get transformation rule and transform the node As a rule may invoke other rules, the document is  processed recursively.
Using PHP‘s XSLT functions Run configure with the --enable-xslt --with-xslt-sablot  options. Create XSLT processor with xslt_create() Apply stylesheet to XML document with xslt_process() (Strings or Files may be used) Free memory with xslt_free() Take a look at the example.
Using PHP‘s XSLT functions $xmlFile =  &quot;xml/helloworld.xml&quot; ; $xslFile =  &quot;xsl/helloworld.xsl&quot; ; if ( !$xp =  xslt_create () ) die (  &quot;XSLT processor could not be created.&quot;  ); if ( $result =  @xslt_process ( $xp, $xmlFile, $xslFile ) ) { echo $result; } else { echo   &quot;An error occured: &quot;  . xslt_error ( $xp ). &quot; (error code &quot; .  xslt_errno ( $xp ). &quot;)&quot; ; } xslt_free ( $xp );
xslt_process() Accepts six parameters: A handle, representing the XSLT processor The name of the file or buffer containing the XML data The name of the file or buffer containing the XSL data The name of the file to save the result to (optional) An associative array of argument buffers (for transforming strings on-the-fly) An associative array of XSLT parameters (may be used as $paramName in stylesheet)
Other XSLT functions xslt_error () and  xslt_errno () to retrieve the last error xslt_set_error_handler () to define a custom error handler (not stable in PHP 4.3) xslt_set_log () to log processor messages to a logfile Too complicated? »  use patXSLT...
patXSLT Soon available for download at  http://www.php-tools.net Simple interface for all  xslt_*  functions: require_once (  &quot;include/patXSLT.php&quot;  ); $proc =  new  patXSLT(); $proc->setXMLFile(  &quot;xml/helloworld.xml&quot;  ); $proc->setXSLFile(  &quot;xsl/helloworld.xsl&quot;  ); $proc->enableLogging(  &quot;logs/xslt.log&quot;  ); $proc->addParam(  &quot;pagetitle &quot; , $pageTitle ); $proc->transform();
XPath expressions Describe parts of an XML document (elements, attributes, text, ...) May be used in select and match attributes of various elements Melting pot of programming languages ($x*4) and Unix-like path expressions (like /page/section/para) Works with the parsed version of XML documents, which means no access to entities and no possibility to decide whether a text node was text or Cdata Example XPath expressions:  „/“ ,  „greetings/greeting“  and  „greeting“
Location Paths One of the most common uses of XPath Always in respect of the context („the current directory“) Relative and absolute expressions (always evaluated from the root node) Simple location paths: <xsl:template match= “/“ >  (root node) <xsl:value-of select= “.“ />  (context node) <xsl:value-of select= “..“ />  (parent node) <xsl:apply-templates select= “greeting“ /> <xsl:apply-templates select= “/page/section“ />
Selecting Things Besides Elements Selecting attributes /page/section/@title Selecting text nodes /page/title/text() Selecting comments and processing instructions /page/comment()  and  /page/processing-instruction()
Example: The World Answers (1) Sample document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting author= &quot;Stephan&quot; > Hello World! </greeting> <greeting author= &quot;World&quot; > Hello Stephan! </greeting> </greetings>
Example: The World Answers (2) <xsl:stylesheet xmlns:xsl =&quot;http://www.w3.org/1999/XSL/Transform&quot;  version= &quot;1.0&quot; > <xsl:output method= &quot;html&quot; /> <xsl:template match= &quot;/&quot; > <html> <body> <xsl:apply-templates select= &quot;greetings/greeting&quot; /> </body> </html> </xsl:template> <xsl:template match= &quot;greeting&quot; > <h1> <xsl:value-of select= &quot;@author&quot; /> <xsl:text>  says:  </xsl:text> <xsl:value-of select= &quot;.&quot; /> </h1> </xsl:template> </xsl:stylesheet>
Example: The World Answers (3)
Axes in a document By  default child axis is used, but there are several axes: Child axis (default) Parent axis (..) Self axis (.) Attribute axis (@) Ancestor axis (ancestor::) Descendant axis (descendant::) Preceding-sibling axis (preceding-sibling::) Following-sibling axis (following-sibling::)
Control Elements <xsl:if test= “...“ >  implements an if statement   The expression in test attribute is converted to a boolean  value. Examples: <xsl:if test= “count(section)&gt;3“ > <xsl:if test= “@title“ > <xsl:choose> ,  <xsl:when>  and  <xsl:otherwise>  implement a switch/case statement. Also used to implement an if-then-else statement. Example needed?
Example: A conversation (2) Sample document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting author= &quot;Stephan&quot; > Hello World! </greeting> <greeting author= &quot;World&quot; > Hello Stephan! </greeting> <greeting> Hello both of you! </greeting> </greetings>
Example: A conversation (1) <xsl:template match= &quot;greeting&quot; > <h1> <xsl:choose> <xsl:when test= &quot;@author&quot; > <xsl:value-of select= &quot;@author&quot; /> <xsl:text>  says:  </xsl:text> <xsl:value-of select= &quot;.&quot; /> </xsl:when> <xsl:otherwise> <xsl:text> Somebody says:  </xsl:text> <xsl:value-of select= &quot;.&quot; /> </xsl:otherwise> </xsl:choose> </h1> </xsl:template>
Example: A conversation (3)
Additional XSLT Features Wildcards (*, @*, //) Predicates (line[3], entry[position() mod 2 = 0]) <xsl:for-each>  to process several nodes <xsl:template mode= “...“ >  and  <xsl:apply-templates mode= “...“ > Parameters, that may be passed with  <xsl:apply-templates>  or  from PHP Variables (may not be changed!) Sorting and grouping
Drawbacks of XSLT Needs to be installed (requires Sablotron) Designer needs to learn XSLT tags The XSLT-processor is a black-box: No possibilty to pause or influence the process once it has started It is not possible to include dynamic content into an XML file while processing.
Transforming XML with PHP HTML Template for each XML element Attribute values are used as template variables The content of an element is a special template variable:  {CONTENT} The XML document is parsed recursively using SAX-based parser
Example <section title= &quot;XML Transformation&quot; > <para> XML may be transformed using PHP. </para> </section> XML Template for  <section> Template for  <para> <table border= &quot;0&quot;  cellpadding= &quot;0&quot;  cellspacing= &quot;2&quot;  width= &quot;500&quot; > <tr><td><b> {TITLE} </b></td><tr> <tr><td> {CONTENT} </td></tr> </table> <font face= &quot; Arial &quot;  size= &quot; 2 &quot; > {CONTENT} <br> </font>
Including Dynamic Content By using callbacks, each PHP function may be used at any time. Simple Example:  <time:current/>  should insert current time. Solution:   switch/case statement in element handler that executes PHP code instead  of replacing the tag with its template. »  code is hard to maintain Improvement:   extensible parser, that invokes callbacks for specific namespaces.
Randy - patXMLRenderer Open source (LGPL License) Uses the template class patTemplate Supports external entities („XML includes“) Unlimited amount of extensions. Tags will be passed to an extension according to namespaces The renderer only transforms static content and content returned by extensions Unlimited amount of designs Other features: caching, logging, etc...
Architecture RENDERER HTML / XML /LaTEX /usw... Any extension XML TEMPLATES Time: Extension Dbc: Extension Ext. Entities
Existing Extensions Repository on  http://www.php-tools.de Documentation is generated automatically Examples: <time:...>  date and time functions <dbc:...>  database interface <var:...>  access to variables <control:...>  control structures <randy:...>  XML-API for patXMLRenderer <file:...>  file operations and many more...
Similar Applications At least two more applications: PEAR::XML_Transformer http:// pear.php.net Only overloads tags with functions and methods. phpTagLib http://chocobot.d2g.com Only transforms XML to HTML.
Comparison - - X Parameters Only with PHP code - X „ Intelligent“ Templates - All in one package X Ext. Repository - - X Administration X - X <?PHP ?> - - X External Entities - Yes, infinite Yes, infinite Recursion - X X Namespaces - Yes, objects and functions Yes, only object Dynamic Content (Callbacks) yes, plain HTML - yes, patTemplate Templates phpTagLib PEAR patXMLRenderer
XSLT vs PHP Transformers Pro XSLT: Much faster than PHP transformers W3C Standard (works with any XSLT Processor) Pro PHP Transfomers: Easily extendable Easier to learn Script has complete control during the transformation process
The End Thank you! More information: http://www.php-tools.net [email_address] Thanks to: Sebastian Mordziol, Gerd Schaufelberger, Stephan Eisler,  Metrix Internet Design GmbH

More Related Content

PPT
Component and Event-Driven Architectures in PHP
PPT
The Big Documentation Extravaganza
PPT
XML Transformations With PHP
PPT
PEAR For The Masses
PPT
XML and Web Services with PHP5 and PEAR
PPT
XML and PHP 5
PPT
Session Server - Maintaing State between several Servers
PPT
Go OO! - Real-life Design Patterns in PHP 5
Component and Event-Driven Architectures in PHP
The Big Documentation Extravaganza
XML Transformations With PHP
PEAR For The Masses
XML and Web Services with PHP5 and PEAR
XML and PHP 5
Session Server - Maintaing State between several Servers
Go OO! - Real-life Design Patterns in PHP 5

What's hot (20)

PPT
PDF Localization
PPT
AdvancedXPath
PPT
ImplementingChangeTrackingAndFlagging
PPT
Debugging and Error handling
PPT
LocalizingStyleSheetsForHTMLOutputs
PPTX
Ot performance webinar
PPT
C:\Users\User\Desktop\Eclipse Infocenter
PPT
Open Source Package Php Mysql 1228203701094763 9
PPTX
Dost.jar and fo.jar
PPT
PPSX
Php and MySQL
PDF
lf-2003_01-0269
PPT
Phpwebdev
ODP
Architecting Web Services
PPT
Overview of PHP and MYSQL
PDF
Web Development Course: PHP lecture 1
PPT
Php Simple Xml
PPT
PHP Presentation
DOCX
PHP NOTES FOR BEGGINERS
PPT
Php mysql
PDF Localization
AdvancedXPath
ImplementingChangeTrackingAndFlagging
Debugging and Error handling
LocalizingStyleSheetsForHTMLOutputs
Ot performance webinar
C:\Users\User\Desktop\Eclipse Infocenter
Open Source Package Php Mysql 1228203701094763 9
Dost.jar and fo.jar
Php and MySQL
lf-2003_01-0269
Phpwebdev
Architecting Web Services
Overview of PHP and MYSQL
Web Development Course: PHP lecture 1
Php Simple Xml
PHP Presentation
PHP NOTES FOR BEGGINERS
Php mysql
Ad

Similar to Inroduction to XSLT with PHP4 (20)

PPT
Introduction to XML
PPT
PPT
XML and XSLT
PPT
5 xsl (formatting xml documents)
PPT
Processing XML with Java
PPT
Digital + Container List
PPT
Everything You Always Wanted To Know About XML But Were Afraid To Ask
PPT
PPT
PPT
Extensible Stylesheet Language
PPT
Transforming Xml Data Into Html
PPT
Introduction to XML
PPT
Week 12 xml and xsl
PPT
PPT
6 311 W
PPT
6 311 W
PPT
Sax Dom Tutorial
PPT
Java XML Parsing
PPT
Xslt by asfak mahamud
PPT
XML processing with perl
Introduction to XML
XML and XSLT
5 xsl (formatting xml documents)
Processing XML with Java
Digital + Container List
Everything You Always Wanted To Know About XML But Were Afraid To Ask
Extensible Stylesheet Language
Transforming Xml Data Into Html
Introduction to XML
Week 12 xml and xsl
6 311 W
6 311 W
Sax Dom Tutorial
Java XML Parsing
Xslt by asfak mahamud
XML processing with perl
Ad

More from Stephan Schmidt (17)

PDF
Das Web Wird Mobil - Geolocation und Location Based Services
PDF
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
PDF
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
PDF
Continuous Integration mit Jenkins
PDF
Die Kunst des Software Design - Java
PDF
PHP mit Paul Bocuse
PDF
Der Erfolgreiche Programmierer
PDF
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
KEY
Die Kunst Des Software Design
PDF
Software-Entwicklung Im Team
PDF
JSON-RPC Proxy Generation with PHP 5
PPT
Declarative Development Using Annotations In PHP
PPT
XML-Socket-Server zur Kommunikation mit Flash
PPT
Interprozesskommunikation mit PHP
PPT
PHP im High End
PPT
Dynamische Websites mit XML
PPT
Web 2.0 Mit Der Yahoo User Interface Library
Das Web Wird Mobil - Geolocation und Location Based Services
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
Continuous Integration mit Jenkins
Die Kunst des Software Design - Java
PHP mit Paul Bocuse
Der Erfolgreiche Programmierer
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
Die Kunst Des Software Design
Software-Entwicklung Im Team
JSON-RPC Proxy Generation with PHP 5
Declarative Development Using Annotations In PHP
XML-Socket-Server zur Kommunikation mit Flash
Interprozesskommunikation mit PHP
PHP im High End
Dynamische Websites mit XML
Web 2.0 Mit Der Yahoo User Interface Library

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
Mobile App Security Testing_ A Comprehensive Guide.pdf
Approach and Philosophy of On baking technology
sap open course for s4hana steps from ECC to s4
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Dropbox Q2 2025 Financial Results & Investor Presentation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
cuic standard and advanced reporting.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Empathic Computing: Creating Shared Understanding
Encapsulation_ Review paper, used for researhc scholars
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MYSQL Presentation for SQL database connectivity
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Digital-Transformation-Roadmap-for-Companies.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction

Inroduction to XSLT with PHP4

  • 1. Introduction to XSLT with PHP4 PHPCon 2002 10/25/2002, Millbrae California USA Stephan Schmidt
  • 2. Table of Contents About the speaker Structuring content XML basics Introduction to XSLT Using PHP‘s XSLT functions Advanced XSLT Drawbacks of XSLT Transforming XML without XSLT patXMLRenderer Similar applications
  • 3. Stephan Schmidt Web application developer since 1999 Working for Metrix Internet Design GmbH in Germany Maintainer of www.php-tools.net Author of patTemplate, patXMLRenderer, patUser and others Focussing on the combination of XML and PHP and the separation of content and layout
  • 4. Separation of content and layout Why? Modify layout without accessing content Modify content without accessing layout Different views for different devices (Browser, mobile phone,…) Different views for different user types (visitor, client, administrator) How? Different approaches…
  • 5. Structuring content Classic websites and the use of HTML: » no structure at all » not readable by machines Classic software-development uses RDBMs: » hardly readable by humans Use of relations to implement structure Use of several table (normalization) Use of cryptic IDs
  • 6. Using XML for structured data Readable by humans: » complete data in one file » self-explaining tag names » self-explaining attribute names » structured by indentation Readable by machines: » Well-formed document » only ASCII data » Validation with DTD or schema Separation of content and layout
  • 7. Building a content structure 1 Split content into logical elements navigation Sections and parargraphs Lists and list elements Tags should describe their content, e.g. use <important> for important parts in you page No layout-elements like <br>, use <p>...</p> instead Define and write down page structure XML Schema DTD
  • 8. Building a content structure 2
  • 9. Building a content structure 3
  • 10. Building a content structure 4
  • 11. Basic XML Rules Each document needs a root element Each tag has to be closed, i.e. <p>…</p> instead of just <p> Use trailing slash to indicate an empty element (<br/> instead of <br>) Elements may not overlap (<p>…<b>…</b>…</p> instead of <p>…<b>…</p>…</b>) Attribute values have to be enclosed in double quotes Entities for <, >, &, “ and ‘ have to be used
  • 12. XML Example <page> <headline> Introduction to XSLT </headline> <section title=&quot;Abstract&quot;> <para> The presentation includes </para> <list> <listelement> Examples </listelement> <listelement> Some PHP code </listelement> </list> </section> <section title=&quot;About the author&quot;> <para> Web developer from Germany </para> </section> </page>
  • 13. Tree view of a document Each piece of information in an XML document is referred to as a node: Element Nodes (tags) Attribute Nodes (attributes of a tag) Text Nodes (text and Cdata sections) Comment Nodes (<!-- ... -->) Processing Instruction Nodes (<?PHP ... ?>) Namespace Nodes (xmlns:myns=“...“)
  • 14. Tree view of a document (example)
  • 15. XML Transformations Each tag has to be transformed into an HTML representation: <headline> Introduction to XSLT </headline> … is transformed to: <font size=&quot;+1&quot;> <br><b> Introduction to XSLT </b><br><br> </font>
  • 16. Introduction to XSLT Stylesheet must be an XML document (well-formed and valid) Based on pattern-matching („When you see something that looks like this, do something else“) Free of sideeffects (One rule may not influence or modify others) Use of iteration and recursion
  • 17. „ Hello World“ Example (XML) Sample Document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting> Hello World! </greeting> </greetings>
  • 18. „ Hello World“ Example (XSL) <xsl:stylesheet xmlns:xsl= &quot;http://www.w3.org/1999/XSL/Transform&quot; version= &quot;1.0&quot; > <xsl:output method= &quot;html&quot; /> <xsl:template match= &quot;/&quot; > <html> <body> <xsl:apply-templates select= &quot;greetings/greeting&quot; /> </body> </html> </xsl:template> <xsl:template match= &quot;greeting&quot; > <h1> <xsl:value-of select= &quot;.&quot; /> </h1> </xsl:template> </xsl:stylesheet>
  • 19. „ Hello World“ Example (Output)
  • 20. Closer look at the XSL template <xsl:stylesheet> root element and its attributes are mandatory <xsl:output/> defines output format (sets some properties in the XSLT processor ) Two <xsl:template> tags define how XML elements are transformed <xsl:apply-templates> invokes other templates
  • 21. Transformation Workflow Read stylesheet, so that each part may be easily accessed Read the XML document and build tree view of the document Transform the document Check for nodes to process („the context“) Get the next node from the context Get transformation rule and transform the node As a rule may invoke other rules, the document is processed recursively.
  • 22. Using PHP‘s XSLT functions Run configure with the --enable-xslt --with-xslt-sablot options. Create XSLT processor with xslt_create() Apply stylesheet to XML document with xslt_process() (Strings or Files may be used) Free memory with xslt_free() Take a look at the example.
  • 23. Using PHP‘s XSLT functions $xmlFile = &quot;xml/helloworld.xml&quot; ; $xslFile = &quot;xsl/helloworld.xsl&quot; ; if ( !$xp = xslt_create () ) die ( &quot;XSLT processor could not be created.&quot; ); if ( $result = @xslt_process ( $xp, $xmlFile, $xslFile ) ) { echo $result; } else { echo &quot;An error occured: &quot; . xslt_error ( $xp ). &quot; (error code &quot; . xslt_errno ( $xp ). &quot;)&quot; ; } xslt_free ( $xp );
  • 24. xslt_process() Accepts six parameters: A handle, representing the XSLT processor The name of the file or buffer containing the XML data The name of the file or buffer containing the XSL data The name of the file to save the result to (optional) An associative array of argument buffers (for transforming strings on-the-fly) An associative array of XSLT parameters (may be used as $paramName in stylesheet)
  • 25. Other XSLT functions xslt_error () and xslt_errno () to retrieve the last error xslt_set_error_handler () to define a custom error handler (not stable in PHP 4.3) xslt_set_log () to log processor messages to a logfile Too complicated? » use patXSLT...
  • 26. patXSLT Soon available for download at http://www.php-tools.net Simple interface for all xslt_* functions: require_once ( &quot;include/patXSLT.php&quot; ); $proc = new patXSLT(); $proc->setXMLFile( &quot;xml/helloworld.xml&quot; ); $proc->setXSLFile( &quot;xsl/helloworld.xsl&quot; ); $proc->enableLogging( &quot;logs/xslt.log&quot; ); $proc->addParam( &quot;pagetitle &quot; , $pageTitle ); $proc->transform();
  • 27. XPath expressions Describe parts of an XML document (elements, attributes, text, ...) May be used in select and match attributes of various elements Melting pot of programming languages ($x*4) and Unix-like path expressions (like /page/section/para) Works with the parsed version of XML documents, which means no access to entities and no possibility to decide whether a text node was text or Cdata Example XPath expressions: „/“ , „greetings/greeting“ and „greeting“
  • 28. Location Paths One of the most common uses of XPath Always in respect of the context („the current directory“) Relative and absolute expressions (always evaluated from the root node) Simple location paths: <xsl:template match= “/“ > (root node) <xsl:value-of select= “.“ /> (context node) <xsl:value-of select= “..“ /> (parent node) <xsl:apply-templates select= “greeting“ /> <xsl:apply-templates select= “/page/section“ />
  • 29. Selecting Things Besides Elements Selecting attributes /page/section/@title Selecting text nodes /page/title/text() Selecting comments and processing instructions /page/comment() and /page/processing-instruction()
  • 30. Example: The World Answers (1) Sample document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting author= &quot;Stephan&quot; > Hello World! </greeting> <greeting author= &quot;World&quot; > Hello Stephan! </greeting> </greetings>
  • 31. Example: The World Answers (2) <xsl:stylesheet xmlns:xsl =&quot;http://www.w3.org/1999/XSL/Transform&quot; version= &quot;1.0&quot; > <xsl:output method= &quot;html&quot; /> <xsl:template match= &quot;/&quot; > <html> <body> <xsl:apply-templates select= &quot;greetings/greeting&quot; /> </body> </html> </xsl:template> <xsl:template match= &quot;greeting&quot; > <h1> <xsl:value-of select= &quot;@author&quot; /> <xsl:text> says: </xsl:text> <xsl:value-of select= &quot;.&quot; /> </h1> </xsl:template> </xsl:stylesheet>
  • 32. Example: The World Answers (3)
  • 33. Axes in a document By default child axis is used, but there are several axes: Child axis (default) Parent axis (..) Self axis (.) Attribute axis (@) Ancestor axis (ancestor::) Descendant axis (descendant::) Preceding-sibling axis (preceding-sibling::) Following-sibling axis (following-sibling::)
  • 34. Control Elements <xsl:if test= “...“ > implements an if statement  The expression in test attribute is converted to a boolean value. Examples: <xsl:if test= “count(section)&gt;3“ > <xsl:if test= “@title“ > <xsl:choose> , <xsl:when> and <xsl:otherwise> implement a switch/case statement. Also used to implement an if-then-else statement. Example needed?
  • 35. Example: A conversation (2) Sample document: <?xml version=&quot;1.0&quot;?> <greetings> <greeting author= &quot;Stephan&quot; > Hello World! </greeting> <greeting author= &quot;World&quot; > Hello Stephan! </greeting> <greeting> Hello both of you! </greeting> </greetings>
  • 36. Example: A conversation (1) <xsl:template match= &quot;greeting&quot; > <h1> <xsl:choose> <xsl:when test= &quot;@author&quot; > <xsl:value-of select= &quot;@author&quot; /> <xsl:text> says: </xsl:text> <xsl:value-of select= &quot;.&quot; /> </xsl:when> <xsl:otherwise> <xsl:text> Somebody says: </xsl:text> <xsl:value-of select= &quot;.&quot; /> </xsl:otherwise> </xsl:choose> </h1> </xsl:template>
  • 38. Additional XSLT Features Wildcards (*, @*, //) Predicates (line[3], entry[position() mod 2 = 0]) <xsl:for-each> to process several nodes <xsl:template mode= “...“ > and <xsl:apply-templates mode= “...“ > Parameters, that may be passed with <xsl:apply-templates> or from PHP Variables (may not be changed!) Sorting and grouping
  • 39. Drawbacks of XSLT Needs to be installed (requires Sablotron) Designer needs to learn XSLT tags The XSLT-processor is a black-box: No possibilty to pause or influence the process once it has started It is not possible to include dynamic content into an XML file while processing.
  • 40. Transforming XML with PHP HTML Template for each XML element Attribute values are used as template variables The content of an element is a special template variable: {CONTENT} The XML document is parsed recursively using SAX-based parser
  • 41. Example <section title= &quot;XML Transformation&quot; > <para> XML may be transformed using PHP. </para> </section> XML Template for <section> Template for <para> <table border= &quot;0&quot; cellpadding= &quot;0&quot; cellspacing= &quot;2&quot; width= &quot;500&quot; > <tr><td><b> {TITLE} </b></td><tr> <tr><td> {CONTENT} </td></tr> </table> <font face= &quot; Arial &quot; size= &quot; 2 &quot; > {CONTENT} <br> </font>
  • 42. Including Dynamic Content By using callbacks, each PHP function may be used at any time. Simple Example: <time:current/> should insert current time. Solution: switch/case statement in element handler that executes PHP code instead of replacing the tag with its template. » code is hard to maintain Improvement: extensible parser, that invokes callbacks for specific namespaces.
  • 43. Randy - patXMLRenderer Open source (LGPL License) Uses the template class patTemplate Supports external entities („XML includes“) Unlimited amount of extensions. Tags will be passed to an extension according to namespaces The renderer only transforms static content and content returned by extensions Unlimited amount of designs Other features: caching, logging, etc...
  • 44. Architecture RENDERER HTML / XML /LaTEX /usw... Any extension XML TEMPLATES Time: Extension Dbc: Extension Ext. Entities
  • 45. Existing Extensions Repository on http://www.php-tools.de Documentation is generated automatically Examples: <time:...> date and time functions <dbc:...> database interface <var:...> access to variables <control:...> control structures <randy:...> XML-API for patXMLRenderer <file:...> file operations and many more...
  • 46. Similar Applications At least two more applications: PEAR::XML_Transformer http:// pear.php.net Only overloads tags with functions and methods. phpTagLib http://chocobot.d2g.com Only transforms XML to HTML.
  • 47. Comparison - - X Parameters Only with PHP code - X „ Intelligent“ Templates - All in one package X Ext. Repository - - X Administration X - X <?PHP ?> - - X External Entities - Yes, infinite Yes, infinite Recursion - X X Namespaces - Yes, objects and functions Yes, only object Dynamic Content (Callbacks) yes, plain HTML - yes, patTemplate Templates phpTagLib PEAR patXMLRenderer
  • 48. XSLT vs PHP Transformers Pro XSLT: Much faster than PHP transformers W3C Standard (works with any XSLT Processor) Pro PHP Transfomers: Easily extendable Easier to learn Script has complete control during the transformation process
  • 49. The End Thank you! More information: http://www.php-tools.net [email_address] Thanks to: Sebastian Mordziol, Gerd Schaufelberger, Stephan Eisler, Metrix Internet Design GmbH