HTMLXSLTProcessor.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Decorator/extender XSLT processor specifically for HTML documents.
  4. */
  5. class ConfigDoc_HTMLXSLTProcessor
  6. {
  7. /**
  8. * Instance of XSLTProcessor
  9. */
  10. protected $xsltProcessor;
  11. public function __construct($proc = false) {
  12. if ($proc === false) $proc = new XSLTProcessor();
  13. $this->xsltProcessor = $proc;
  14. }
  15. /**
  16. * @note Allows a string $xsl filename to be passed
  17. */
  18. public function importStylesheet($xsl) {
  19. if (is_string($xsl)) {
  20. $xsl_file = $xsl;
  21. $xsl = new DOMDocument();
  22. $xsl->load($xsl_file);
  23. }
  24. return $this->xsltProcessor->importStylesheet($xsl);
  25. }
  26. /**
  27. * Transforms an XML file into compatible XHTML based on the stylesheet
  28. * @param $xml XML DOM tree, or string filename
  29. * @return string HTML output
  30. * @todo Rename to transformToXHTML, as transformToHTML is misleading
  31. */
  32. public function transformToHTML($xml) {
  33. if (is_string($xml)) {
  34. $dom = new DOMDocument();
  35. $dom->load($xml);
  36. } else {
  37. $dom = $xml;
  38. }
  39. $out = $this->xsltProcessor->transformToXML($dom);
  40. // fudges for HTML backwards compatibility
  41. // assumes that document is XHTML
  42. $out = str_replace('/>', ' />', $out); // <br /> not <br/>
  43. $out = str_replace(' xmlns=""', '', $out); // rm unnecessary xmlns
  44. if (class_exists('Tidy')) {
  45. // cleanup output
  46. $config = array(
  47. 'indent' => true,
  48. 'output-xhtml' => true,
  49. 'wrap' => 80
  50. );
  51. $tidy = new Tidy;
  52. $tidy->parseString($out, $config, 'utf8');
  53. $tidy->cleanRepair();
  54. $out = (string) $tidy;
  55. }
  56. return $out;
  57. }
  58. /**
  59. * Bulk sets parameters for the XSL stylesheet
  60. * @param array $options Associative array of options to set
  61. */
  62. public function setParameters($options) {
  63. foreach ($options as $name => $value) {
  64. $this->xsltProcessor->setParameter('', $name, $value);
  65. }
  66. }
  67. /**
  68. * Forward any other calls to the XSLT processor
  69. */
  70. public function __call($name, $arguments) {
  71. call_user_func_array(array($this->xsltProcessor, $name), $arguments);
  72. }
  73. }
  74. // vim: et sw=4 sts=4