QPXSL.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /** @file
  3. * Provide QueryPath with XSLT support using the PHP libxslt module.
  4. *
  5. * This is called 'QPXSL' instead of 'QPXSLT' in accordance with the name
  6. * of the PHP extension that provides libxslt support.
  7. *
  8. * You must have PHP XSL support for this to function.
  9. *
  10. * @author M Butcher <matt@aleph-null.tv>
  11. * @license http://opensource.org/licenses/lgpl-2.1.php LGPL or MIT-like license.
  12. * @see QueryPathExtension
  13. * @see QueryPathExtensionRegistry::extend()
  14. * @see QPXSL
  15. * @see QPXML
  16. */
  17. /**
  18. * Provide tools for running XSL Transformation (XSLT) on a document.
  19. *
  20. * This extension provides the {@link QPXSL::xslt()} function, which transforms
  21. * a source XML document into another XML document according to the rules in
  22. * an XSLT document.
  23. *
  24. * This QueryPath extension can be used as follows:
  25. * <code>
  26. * <?php
  27. * require 'QueryPath/QueryPath.php';
  28. * require 'QueryPath/Extension/QPXSL.php';
  29. *
  30. * qp('src.xml')->xslt('stylesheet.xml')->writeXML();
  31. * ?>
  32. *
  33. * This will transform src.xml according to the XSLT rules in
  34. * stylesheet.xml. The results are returned as a QueryPath object, which
  35. * is written to XML using {@link QueryPath::writeXML()}.
  36. * </code>
  37. *
  38. * @ingroup querypath_extensions
  39. */
  40. class QPXSL implements QueryPathExtension {
  41. protected $src = NULL;
  42. public function __construct(QueryPath $qp) {
  43. $this->src = $qp;
  44. }
  45. /**
  46. * Given an XSLT stylesheet, run a transformation.
  47. *
  48. * This will attempt to read the provided stylesheet and then
  49. * execute it on the current source document.
  50. *
  51. * @param mixed $style
  52. * This takes a QueryPath object or <em>any</em> of the types that the
  53. * {@link qp()} function can take.
  54. * @return QueryPath
  55. * A QueryPath object wrapping the transformed document. Note that this is a
  56. * <i>different</em> document than the original. As such, it has no history.
  57. * You cannot call {@link QueryPath::end()} to undo a transformation. (However,
  58. * the original source document will remain unchanged.)
  59. */
  60. public function xslt($style) {
  61. if (!($style instanceof QueryPath)) {
  62. $style = qp($style);
  63. }
  64. $sourceDoc = $this->src->top()->get(0)->ownerDocument;
  65. $styleDoc = $style->get(0)->ownerDocument;
  66. $processor = new XSLTProcessor();
  67. $processor->importStylesheet($styleDoc);
  68. return qp($processor->transformToDoc($sourceDoc));
  69. }
  70. }
  71. QueryPathExtensionRegistry::extend('QPXSL');