note 99932 modified in xsltprocessor.transformtoxml by danbrown

From: Date: Mon, 11 Apr 2011 15:38:19 +0000
Subject: note 99932 modified in xsltprocessor.transformtoxml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-178702@lists.php.net to get a copy of this message
Entities are omitted from the output with the code above. The symptom was that &nbsp; -- which should work with UTF-8 encoding -- did not even get to XSLTProcessor, let alone through it. After too much hacking I discovered the simple fix: set substituteEntities to true in the DOMDocument for the XSL file. That is, replace the loading of the xsl document with <?php $xsl = new DOMDocument; $xsl->substituteEntities = true; // <===added line $xsl->load('collection.xsl'); ?> However, this fails when data entries have HTML entity references. (Some database entries may even contain user generated text.) libxml has the pedantic habit of throwing a FATAL error for any undefined entitiy. Solution: hide the entities so libxml doesn't see them. <?php function hideEntities($data) { return str_replace("&", "&amp;", $data); } ?> You could just add this to the example, but it is tidier to define a function to load data into a DOMDocument. This way you don't need entity declarations in catalog.xsl, either. <?php // Added function for Example #1 /** Load an XML file and create a DOMDocument. Handles arbitrary entities, even undefined ones. */ function fileToDOMDoc($filename) { $dom= new DOMDocument; $xmldata = file_get_contents($filename); $xmldata = str_replace("&", "&amp;", $xmldata); // disguise &s going IN to loadXML() $dom->substituteEntities = true; // collapse &s going OUT to transformToXML() $dom->loadXML($xmldata); return $dom; } // Compare with Example #1 Transforming to a string // Load the XML sources $xml = fileToDOMDoc('collection.xml'); $xsl = fileToDOMDoc('collection.xsl'); // Configure the transformer $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); // transform $xml according to the stylesheet $xsl echo $proc->transformToXML($xml); // transform the data ?> --was-- Entities are omitted from the output with the code above. The symptom was that &nbsp; -- which should work with UTF-8 encoding -- did not even get to XSLTProcessor, let alone through it. After too much hacking I discovered the simple fix: set substituteEntities to true in the DOMDocument for the XSL file. That is, replace the loading of the xsl document with <?php $xsl = new DOMDocument; $xsl->substituteEntities = true; // <===added line $xsl->load('collection.xsl'); ?> http://php.net/manual/en/xsltprocessor.transformtoxml.php

« previous php.notes (#178702) next »