/** * Transform a node with a stylesheet. * * @param DOMNode The node to transform. * * @return DOMDocument The resulting DOMDocument. * * @author Noah Fontes <*****@*****.**> * @author David Zülke <*****@*****.**> * @since 1.0.0 */ public function transformToDoc($doc) { $luie = libxml_use_internal_errors(true); libxml_clear_errors(); $result = parent::transformToDoc($doc); // check if result is false, too, as that means the transformation failed for reasons like infinite template recursion if ($result === false || libxml_get_last_error() !== false || count(libxml_get_errors())) { $errors = array(); foreach (libxml_get_errors() as $error) { $errors[] = sprintf('[%s #%d] Line %d: %s', $error->level == LIBXML_ERR_WARNING ? 'Warning' : ($error->level == LIBXML_ERR_ERROR ? 'Error' : 'Fatal'), $error->code, $error->line, $error->message); } libxml_clear_errors(); libxml_use_internal_errors($luie); throw new Exception(sprintf('Error%s occurred while transforming the document using an XSL stylesheet: ' . "\n\n%s", count($errors) > 1 ? 's' : '', implode("\n", $errors))); } libxml_use_internal_errors($luie); // turn this into an instance of the class that was passed in, rather than a regular DOMDocument $class = $doc instanceof DOMDocument ? $doc : ($doc->ownerDocument ?: 'DOMDocument'); $document = new $class(); $document->loadXML($result->saveXML()); // save the URI just in case $document->documentURI = $result->documentURI; unset($result); return $document; }
/** * @param string $xslFile * @param array $xsltParameters * @param Element|Tag|Field|Set $element * @param string $ns namespace * * @return \DOMDocument */ public function transform($xslFile, $xsltParameters = array(), &$element, $ns = '') { $this->load($xslFile, LIBXML_NOCDATA, $result); if (!$result) { return $element; } foreach ($xsltParameters as $name => $value) { $this->processor->setParameter($ns, $name, $value); } if ($element instanceof Set) { $processor = $this->processor; $element->each(function (Element $el) use($processor, $xslFile) { $result = $processor->transformToDoc($el); if (!$result) { $el->after($el->ownerDocument->createComment('not transformed with ' . $xslFile)); } else { $el->replace($result->documentElement, $el); } }); return $element; } $result = $this->processor->transformToDoc($element); if (!$result) { $element->after($element->ownerDocument->createComment('not transformed with ' . $xslFile)); } $element->replace($result->documentElement, $element); return $element; }
/** * Executes Params XSLT (transformation to be used to convert parameters into query) for given query. */ function params() { $document =& JFactory::getDocument(); $viewName = JRequest::getVar('view', 'params'); $viewType = $document->getType(); $view =& $this->getView($viewName, $viewType); $data = JRequest::getVar('data', '', 'post', 'string', JREQUEST_ALLOWRAW); $query_id = JRequest::getInt('id_query', NULL); $result = $data; if ($query_id != NULL && !empty($data)) { $model_queries =& $this->getModel('queries'); $query = $model_queries->getQuery($query_id); if ($query != NULL && !empty($query->paramsxsl)) { $xml = new DOMDocument(); if ($xml->loadXML($data)) { // start xslt $xslt = new XSLTProcessor(); $xsl = new DOMDocument(); $xsl->loadXML($query->paramsxsl); $xslt->importStylesheet($xsl); $paramset = $xslt->transformToDoc($xml); $result = $xslt->transformToXML($xml); if ($result === false) { // TODO: any joomla function for this? header('HTTP/1.1 500 Internal Server Error'); } } } } $view->assign('value', $result); $view->display(); }
protected function doRemoveNamespacedNodes(&$pq) { $xsl = <<<____EOF <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl"> <xsl:template match="*[local-name()=name()]"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@* | node()"/> </xsl:element> </xsl:template> <xsl:template match="@* | text()"> <xsl:copy/> </xsl:template> </xsl:stylesheet> ____EOF; $xsl = \DOMDocument::loadXml($xsl); $proc = new \XSLTProcessor(); $proc->importStyleSheet($xsl); $pq->document = $proc->transformToDoc($pq->document); for ($i = $pq->document->documentElement->attributes->length; $i >= 0; --$i) { $attr = $pq->document->documentElement->attributes->item($i); if (substr($attr->name, 0, 6) === 'xmlns:') { $pq->document->documentElement->removeAttributeNode($attr); } } $pq = PhpQuery::newDocumentHTML($pq->document->saveHTML()); return $this; }
/** * Обрабатывает данные. * @param string $data XML-строка */ public function process($data) { $errorHandler = new \WebConstructionSet\Xml\LibxmlErrorHandler(); $xml = new \DOMDocument(); if (!$xml->loadXML($data)) { throw new \ErrorException('Document parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__); } $xsl = new \DOMDocument(); if ($this->xslString) { if (!$xsl->loadXML($this->xslString)) { throw new \ErrorException('XSL stylesheet load/parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__); } } else { $xslPath = $this->getXslStylesheetPath($xml); if (!$xslPath) { throw new \ErrorException('XSL stylesheet path is not found.', null, null, __FILE__, __LINE__); } if (!$xsl->load($xslPath)) { throw new \ErrorException('XSL stylesheet load/parse failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__); } } $xslt = new \XSLTProcessor(); if (!$xslt->importStylesheet($xsl)) { throw new \ErrorException('Import XSL stylesheet failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__); } $this->resultDoc = $xslt->transformToDoc($xml); if (!$this->resultDoc) { throw new \ErrorException('XSLT transform failed. ' . $errorHandler->getErrorString(), null, null, __FILE__, __LINE__); } // no return }
/** * @Route("/{volume}/{id}", requirements={"id" = "\d+", "volume" = "\d+"}) * @param $volume * @param $id * @param bool|false $showByName * @return \Symfony\Component\HttpFoundation\Response */ public function showArticleById($volume, $id, $showByName = false) { $id_article = 'v' . $volume . '-' . $id; $xml_source = new \DOMDocument(); $xml_source->load('../src/AppBundle/Resources/xml/volume' . $volume . '.xml'); $xslt_root = new \DOMDocument(); $xslt_root->load('../src/AppBundle/Resources/xslt/article.xsl'); $transform = new \XSLTProcessor(); $transform->importStylesheet($xslt_root); $xpath = new \DOMXpath($xml_source); $page_debut_xpath = $xpath->query("//div[@type='article' and @xml:id='" . $id_article . "']/preceding::pb[position()\n =1]"); $num_vue = $page_debut_xpath->item(0)->attributes->item(1)->nodeValue; $page_debut = substr($num_vue, strpos($num_vue, "p") + 1); $article_result = $xpath->query("//div[@type='article' and @xml:id='" . $id_article . "']"); $vedette_adresse_text = $xpath->query("//div[@type='article' and @xml:id='" . $id_article . "']/child::div[position()=1]/child::p[position()=1]/child::seg[@type='vedette_adresse']/descendant::text()"); $vedette_adresse = ''; if ($vedette_adresse_text->length > 0) { for ($i = 0; $i < $vedette_adresse_text->length; $i++) { $vedette_adresse .= $vedette_adresse_text->item($i)->nodeValue; } } $pos_article = null; if ($article_result->length > 0) { $content = $article_result->item(0); $xml_transform = new \DOMDocument(); $xml_transform->appendChild($xml_transform->importNode($content, true)); $article = $transform->transformToDoc($xml_transform)->saveHTML(); $pos_article = intval($id); $next_article = $pos_article + 1; $previous_article = $pos_article - 1; if ($pos_article == 1) { $previous_article = null; } else { if ($showByName) { $previous_article_id = 'v' . $volume . '-' . $previous_article; $previous_article_vedette_adresse_text = $xpath->query("//div[@type='article' and @xml:id='" . $previous_article_id . "']/child::div[position()=1]/child::p[position()=1]/child::seg[@type='vedette_adresse']"); if ($previous_article_vedette_adresse_text->length > 0) { $previous_article = $previous_article_vedette_adresse_text->item(0)->textContent; $previous_article = str_replace(" ", "_", $previous_article); } } } $next_article_id = 'v' . $volume . '-' . $next_article; $xpath_find_next_article = $xpath->query("//div[@type='article' and @xml:id='" . $next_article_id . "']"); if ($xpath_find_next_article->length == 0) { $next_article = null; } else { if ($showByName) { $next_article_vedette_adresse_text = $xpath->query("//div[@type='article' and @xml:id='" . $next_article_id . "']/child::div[position()=1]/child::p[position()=1]/child::seg[@type='vedette_adresse']"); if ($next_article_vedette_adresse_text->length > 0) { $next_article = $next_article_vedette_adresse_text->item(0)->textContent; $next_article = str_replace(" ", "_", $next_article); } } } return $this->render('AppBundle::article.html.twig', array('article' => $article, 'id_article' => $id, 'name_article' => $vedette_adresse, 'next_article' => $next_article, 'previous_article' => $previous_article, 'volume' => $volume, 'first_page' => $page_debut)); } return $this->render('AppBundle::404.html.twig', array('error' => 404)); }
/** * @param \DOMNode $doc * @return DOMDocument */ public function transformToDoc($doc) { $styleSheet = $this->styleSheetToDomDocument(); $transpiler = $this->createTranspiler($styleSheet); parent::importStylesheet($this->getTranspiledStyleSheet($transpiler, $styleSheet)); return $transpiler->transform(function () use($doc) { return parent::transformToDoc($doc); }); }
/** * Process given document into template and render it with given values. * * @param DocumentInterface $document * @param array $values * @return Result */ public function render(DocumentInterface $document, array $values) { // fill with values $xslt = new \XSLTProcessor(); $template = $this->getTemplate($document); $xslt->importStylesheet($template); $content = $xslt->transformToDoc($this->createValuesDocument($values)); Processor::undoEscapeXsl($content); return new Result($content, $document); }
public function xslt($style) { if (!$style instanceof QueryPath) { $style = qp($style); } $sourceDoc = $this->src->top()->get(0)->ownerDocument; $styleDoc = $style->get(0)->ownerDocument; $processor = new XSLTProcessor(); $processor->importStylesheet($styleDoc); return qp($processor->transformToDoc($sourceDoc)); }
public function testTransformToDoc() { $xslDoc = new DOMDocument(); $xslDoc->load('Stubs/collection.xsl'); $xmlDoc = new DOMDocument(); $xmlDoc->load('Stubs/collection.xml'); $native = new \XSLTProcessor(); $native->importStylesheet($xslDoc); $nativeResult = $native->transformToDoc($xmlDoc); $transpiler = new XsltProcessor(); $transpiler->importStylesheet($xslDoc); $transpilerResult = $transpiler->transformToDoc($xmlDoc); $this->assertEquals($nativeResult->saveXML(), $transpilerResult->saveXML()); }
public static function cbd_run() { $proc = new XSLTProcessor(); $proc->importStyleSheet(DOMDocument::load('xsl/cbd.xsl')); global $registerPHPFunctions; if ($registerPHPFunctions) { $proc->registerPHPFunctions($registerPHPFunctions); } $cbd_xml = $proc->transformToDoc(DOMDocument::load('db://?all-data')); $xml = simplexml_import_dom($cbd_xml) or die('import failed'); global $cbd_host, $cbd_db, $cbd_user, $cbd_pwd; $conn_pg = pg_connect("host='{$cbd_host}' dbname={$cbd_db} user={$cbd_user} password={$cbd_pwd}") or die("error on connection to {$cbd_db}"); Importer::_run($xml, $conn_pg); }
/** * @param \DOMDocument $xml * @param bool|string $specificInstance * @param bool $dontEcho * @param bool $dontFillXML * @param bool $normalize * @return bool|string * @throws Exception */ public static function render(&$xml, $specificInstance = false, $dontEcho = false, $dontFillXML = false, $normalize = true) { if ($specificInstance) { $instance = $specificInstance; } elseif (self::$instance) { $instance = self::$instance; } else { $instance = 'main'; } Debugger::addLine("Render start (instance '{$instance}')"); if (!($resource = Resourcer::getInstance('xslt')->compile($instance))) { throw new Exception("XSLT resource not found"); } $xslDom = new \DomDocument(); $xslDom->resolveExternals = true; $xslDom->substituteEntities = true; if (!$xslDom->loadXML($resource)) { throw new Exception("XSLT load problem for instance '{$instance}'"); } $xslProcessor = new \XSLTProcessor(); $xslProcessor->importStylesheet($xslDom); if (!$dontFillXML and !HttpError::$error and !Debugger::$shutdown) { View\XML::fillXML($xml, $instance); } // transform template if ($html = $xslProcessor->transformToDoc($xml)) { if ($normalize) { $html = self::normalize($html); } else { $html->formatOutput = true; $html = $html->saveXML(); } if ($dontEcho) { return $html; } echo $html; self::$rendered = true; if (Debugger::isEnabled()) { echo '<!-- Page rendered in ' . Debugger::getTimer() . ' seconds -->'; } if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } } else { $errormsg = libxml_get_errors(); //error_get_last(); throw new Exception($errormsg ? $errormsg['message'] : "Can't render templates"); } return true; }
/** * Convert documents between two formats * * Convert documents of the given type to the requested type. * * @param ezcDocumentXmlBase $doc * @return ezcDocumentXmlBase */ public function convert($doc) { // Create XSLT processor, if not yet initialized if ($this->xsltProcessor === null) { $stylesheet = new DOMDocument(); $stylesheet->load($this->options->xslt); $this->xsltProcessor = new XSLTProcessor(); $this->xsltProcessor->importStyleSheet($stylesheet); } // Set provided parameters. foreach ($this->options->parameters as $namespace => $parameters) { foreach ($parameters as $option => $value) { $this->xsltProcessor->setParameter($namespace, $option, $value); } } // We want to handle the occured errors ourselves. $oldErrorHandling = libxml_use_internal_errors(true); // Transform input document $dom = $this->xsltProcessor->transformToDoc($doc->getDomDocument()); $errors = $this->options->failOnError ? libxml_get_errors() : null; libxml_clear_errors(); libxml_use_internal_errors($oldErrorHandling); // If there are errors and the error handling is activated throw an // exception with the occured errors. if ($errors) { throw new ezcDocumentErroneousXmlException($errors); } // Reset parameters, so they are not automatically applied to the next // traansformation. foreach ($this->options->parameters as $namespace => $parameters) { foreach ($parameters as $option => $value) { $this->xsltProcessor->removeParameter($namespace, $option); } } // Build document from transformation and return that. return $this->buildDocument($dom); }
public function parse(Session $session) { $chan = new DOMDocument(); $chan->loadXML(mb_convert_encoding($session->bytes, 'HTML-ENTITIES', 'UTF-8')); $sheet = new DOMDocument(); $sheet->load('data/atom2rss/atom2rss.xsl'); /* use stylesheet from this page */ $processor = new XSLTProcessor(); $processor->registerPHPFunctions(); $processor->importStylesheet($sheet); $session->dom = $processor->transformToDoc($chan); $session->xpath = new DOMXPath($session->dom); $session->dom->save('/tmp/atom.xml'); // error_log("RESULT: " . $session->dom->saveXML()); }
/** * На вход подается содержимое трансформируемого XML и XSL шаблона трансформации * * @param string $xml * @param string $xslt * @return \SimpleXMLElement * @throws \Exception */ public function transformToDocument($xml, $xslt) { try { $xmlObj = new \DOMDocument('1.0', 'UTF-8'); $xmlObj->loadXML($xml); $xslObj = new \DOMDocument('1.0', 'UTF-8'); $xslObj->loadXML($xslt); $proc = new \XSLTProcessor(); $proc->importStyleSheet($xslObj); $xmlObject = $proc->transformToDoc($xmlObj); } catch (\Exception $ex) { throw new \Exception('Xslt_Transformer; XSLT Error: ' . $ex->getMessage()); } return $xmlObject; }
/** * @param array $ticket */ public function convertTicket($ticket) { $processor = new \XSLTProcessor(); $xmlSerializer = new XMLSerializer(); $serializedTicket = $xmlSerializer->serialize($ticket); $dom = new \DOMDocument(); $dom->loadXML($serializedTicket); $processor->registerPHPFunctions('config'); try { $stylesheet = new \DOMDocument(); $stylesheet->load(config('printer.XSLTemplatePath')); $processor->importStylesheet($stylesheet); $doc = $processor->transformToDoc($dom); $doc->save(config('printer.foOutputPath')); } catch (\Exception $e) { Log::error($e->getMessage()); } }
function printXML($xmlPath, $xsltPath) { // Load the XML source $xml = new DOMDocument; $xml->load($xmlPath); $xsl = new DOMDocument; $xsl->load($xsltPath); // Configure the transformer $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); // attach the xsl rules $file = $proc->transformToDoc($xml);//transform xml to doc return $file->saveHTML();//return as html doc }
/** * Returns a DOMDocument with this view's processed structure and Style * Stylesheets, the result is expected to be an XSL-FO document portion, if * we are using <i>children</i> nodes in config i.e. a tree hierarchy report * defnition, or a complete XSL-FO document of we ar not ussing children in * config, i.e. this is a monolitic report. * * @see BasicView::_renderedDom * @return DOMDocument */ public function render() { // Renders this view's $_structure xsl separately from this view's childs. $structTran = $this->_logicalScreenBranch; // die(var_dump($structTran->saveXML())); if (null !== $this->_structure) { self::$_xsltProcessor->importStylesheet($this->_structure); $this->_applyStructureParams(); $structTran = self::$_xsltProcessor->transformToDoc($this->_logicalScreenBranch); } if (null !== $this->_style) { self::$_xsltProcessor->importStylesheet($this->_style); $this->_applyStyleParams(); $structTran = self::$_xsltProcessor->transformToDoc($structTran); } $this->_renderedDom = $structTran; return $this->_renderedDom; }
public function convert($destination, $destinationNs, array $nsMap, array $allowMap, $ext = 'xml') { if (is_dir($destination)) { throw new \RuntimeException("Destination could not be a directory."); } if (!$nsMap) { throw new \RuntimeException(__CLASS__ . " requires at least one ns-map (for {$destinationNs} namespace)."); } $files = array(); foreach ($nsMap as $value) { $dir = rtrim($value["dir"], "\\//"); TypeMapper::addNamespace($value["phpNs"], $value["xmlNs"]); $files = array_merge($files, glob("{$dir}/*.{$ext}")); } $dom = new \DOMDocument('1.0', 'UTF-8'); $root = $dom->createElement('root'); $dom->appendChild($root); foreach ($files as $file) { $mapping = new \DOMDocument('1.0', 'UTF-8'); $mapping->load($file); $newnode = $dom->importNode($mapping->documentElement, true); $root->appendChild($newnode); } $this->handleAllowMap($allowMap, $dom); $xsd = new \DOMDocument('1.0', 'UTF-8'); $xsd->load(__DIR__ . '/../Resources/xsd/convert.xsl'); $processor = new \XSLTProcessor(); $processor->registerPHPFunctions(); $processor->setParameter('', 'targetNs', $destinationNs); $processor->importStylesheet($xsd); $newDom = $processor->transformToDoc($dom); $this->fixXsd($newDom, $destinationNs); $ret = $newDom->save($destination); if ($ret > 0) { return true; } else { return false; } }
/** * Transforms XML document using XSLT. * @param DOMDocument $xmlDom source XML * @param DOMDocument $xsltDom source XSLT * @param string $outputFilenameBase base of output file with transformed XML * to be created * @return bool true on success */ protected function checkXsltValidity(DOMDocument $xmlDom, DOMDocument $xsltDom, $outputFilenameBase) { $this->useLibxmlErrors(); $proc = new XSLTProcessor(); $proc->importStylesheet($xsltDom); if (!$this->failGoalOnLibxmlErrors(self::goalValidXslt, null)) { return false; } $this->useLibxmlErrors(); $newXmlDom = $proc->transformToDoc($xmlDom); if (!$this->reachGoalOnNoLibxmlErrors(self::goalValidXslt, null)) { return false; } $output = $newXmlDom->saveHTML(); $suffix = '.html'; if (!$output) { $output = $newXmlDom->saveXML(); $suffix = '.xml'; } Filesystem::stringToFile($outputFilenameBase . $suffix, $output); return true; }
/** * Shows the sitemap. Main entry point from HTTP * @param string $options Options for the sitemap. What type, what parameters. * @since 4.0 */ public function ShowSitemap($options) { $startTime = microtime(true); $startQueries = $GLOBALS["wpdb"]->num_queries; $startMemory = memory_get_peak_usage(true); //Raise memory and time limits if ($this->GetOption("b_memory") != '') { @ini_set("memory_limit", $this->GetOption("b_memory")); } if ($this->GetOption("b_time") != -1) { @set_time_limit($this->GetOption("b_time")); } do_action("sm_init", $this); $this->isActive = true; $parsedOptions = array(); $options = explode(";", $options); foreach ($options as $k) { $kv = explode("=", $k); $parsedOptions[$kv[0]] = @$kv[1]; } $options = $parsedOptions; $this->buildOptions = $options; //Do not index the actual XML pages, only process them. //This avoids that the XML sitemaps show up in the search results. if (!headers_sent()) { header('X-Robots-Tag: noindex', true, 200); } $this->Initate(); $html = (isset($options["html"]) ? $options["html"] : false) && $this->IsXslEnabled(); if ($html && !$this->GetOption('b_html')) { $GLOBALS['wp_query']->is_404 = true; return; } //Don't zip if anything happened before which could break the output or if the client does not support gzip. //If there are already other output filters, there might be some content on another //filter level already, which we can't detect. Zipping then would lead to invalid content. $pack = isset($options['zip']) ? $options['zip'] : $this->GetOption('b_autozip'); if (empty($_SERVER['HTTP_ACCEPT_ENCODING']) || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false || !$this->IsGzipEnabled() || headers_sent() || ob_get_contents() || in_array('ob_gzhandler', ob_list_handlers()) || $this->GetPhpIniBoolean(ini_get("zlib.output_compression")) || ob_get_level() > (!$this->GetPhpIniBoolean(ini_get("output_buffering")) ? 0 : 1) || isset($_SERVER['HTTP_X_VARNISH']) && is_numeric($_SERVER['HTTP_X_VARNISH'])) { $pack = false; } $packed = false; if ($pack) { $packed = @ob_start('ob_gzhandler'); } $builders = array('sitemap-builder.php'); foreach ($builders as $b) { $f = trailingslashit(dirname(__FILE__)) . $b; if (file_exists($f)) { require_once $f; } } if ($html) { ob_start(); } else { header('Content-Type: text/xml; charset=utf-8'); } if (empty($options["params"]) || $options["params"] == "index") { $this->BuildSitemapHeader("index"); do_action('sm_build_index', $this); $this->BuildSitemapFooter("index"); $this->AddEndCommend($startTime, $startQueries, $startMemory); } else { $allParams = $options["params"]; $type = $params = null; if (strpos($allParams, "-") !== false) { $type = substr($allParams, 0, strpos($allParams, "-")); $params = substr($allParams, strpos($allParams, "-") + 1); } else { $type = $allParams; } $this->BuildSitemapHeader("sitemap"); do_action("sm_build_content", $this, $type, $params); $this->BuildSitemapFooter("sitemap"); $this->AddEndCommend($startTime, $startQueries, $startMemory); } if ($html) { $xmlSource = ob_get_clean(); // Load the XML source $xml = new DOMDocument(); $xml->loadXML($xmlSource); $xsl = new DOMDocument(); $xsl->load($this->GetPluginPath() . "sitemap.xsl"); // Configure the transformer $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); // attach the xsl rules $domTranObj = $proc->transformToDoc($xml); // this will also output doctype and comments at top level foreach ($domTranObj->childNodes as $node) { echo $domTranObj->saveXML($node) . "\n"; } } if ($packed) { ob_end_flush(); } $this->isActive = false; exit; }
/** * Transform the wsdl document using XSL. * * The result is a DOMDocument containing transformed WSDL elements for * generating class files. * * @param DOMNode $dom the dom document * @param string $xslFilePath the file path of the xsl to apply * @param string|null $saveOutputTo the output file to save the result to */ protected function transformWsdl($xslFilePath, $saveOutputTo = null) { $transformedDom = null; $xsl = new XSLTProcessor(); $xslDom = new DOMDocument(); try { $xslDom->load($xslFilePath); $xsl->registerPHPFunctions(); $xsl->importStyleSheet($xslDom); $transformedDom = $xsl->transformToDoc($this->dom); if ($saveOutputTo) { $transformedDom->formatOutput = true; $transformedDom->save($saveOutputTo); } } catch (Exception $e) { throw new WSDLInterpreterException(sprintf("Error interpreting WSDL " . "document (%s)", $e->getMessage())); } $this->dom = $transformedDom; }
/** * Returns an array of available chapters, or 'unknown' if none * * @return array Chapter titles */ protected function getFuzzyChapterTitles() { $chapters = array(); // get the path to the content and the content $doc_path = $this->getTargetPath(self::DOCUMENT_SCHEMA); $xml = $this->getZipContent($doc_path); // introduce a stylesheet $proc = new \XSLTProcessor(); $xsl = new \DOMDocument(); $xsl->load(__DIR__ . '/xsl/docx2html.xsl'); $proc->importStylesheet($xsl); // throw it back into the DOM $dom_doc = $proc->transformToDoc($xml); // get all headings $headings = $dom_doc->getElementsByTagName($this->tag); // populate chapters with title names for ($i = 0; $i < $headings->length; $i++) { $chapters[] = trim($headings->item($i)->nodeValue); } // get rid of h1 tags with empty values $chapters = array_values(array_filter($chapters)); // default chapter title if there are no h1 headings in the document if (0 == count($chapters)) { $chapters[] = '__UNKNOWN__'; } return $chapters; }
<?php $dir = dirname(dirname(__FILE__)); $xsl = new DOMDocument(); $xsl->load($dir . "/xsl/namedEntitiesMarkUp.xsl"); $files = glob($dir . "/tei/*.xml"); foreach ($files as $file) { $file_name = basename($file); $inputdom = new DomDocument(); $inputdom->load($file); $proc = new XSLTProcessor(); $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($inputdom); $newdom->save($dir . "/tei/" . $file_name); }
/** * @param string $results * @param KalturaGenericDistributionProviderParser $resultParserType * @param string $resultParseData * @return array of parsed values */ protected function parseResults($results, $resultParserType, $resultParseData) { switch ($resultParserType) { case KalturaGenericDistributionProviderParser::XSL: $xml = new DOMDocument(); if (!$xml->loadXML($results)) { return false; } $xsl = new DOMDocument(); $xsl->loadXML($resultParseData); $proc = new XSLTProcessor(); $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions()); $proc->importStyleSheet($xsl); $data = $proc->transformToDoc($xml); if (!$data) { return false; } return explode(',', $data); case KalturaGenericDistributionProviderParser::XPATH: $xml = new DOMDocument(); if (!$xml->loadXML($results)) { return false; } $xpath = new DOMXPath($xml); $elements = $xpath->query($resultParseData); if (is_null($elements)) { return false; } $matches = array(); foreach ($elements as $element) { $matches[] = $element->textContent; } return $matches; case KalturaGenericDistributionProviderParser::REGEX: $matches = array(); if (!preg_match("/{$resultParseData}/", $results, $matches)) { return false; } return array_shift($matches); default: return false; } }
/** * Use PHP5's DOMDocument and XSLTProcessor to do the transformation * @param $xml mixed * @param $xmlType integer * @param $xsl mixed * @param $xslType integer * @param $resultType integer * @return mixed return type depends on the $returnType parameter and can be * DOMDocument or string. Returns boolean "false" on error. */ function &_transformPHP5(&$xml, $xmlType, &$xsl, $xslType, $resultType) { // Prepare the XML DOM if ($xmlType == XSL_TRANSFORMER_DOCTYPE_DOM) { // We already have a DOM document, no need to create one assert(is_a($xml, 'DOMDocument')); $xmlDOM =& $xml; } else { // Instantiate and configure the XML DOM document $xmlDOM = new DOMDocument('1.0', XSLT_PROCESSOR_ENCODING); // These are required for external entity resolution (eg. ), but can slow processing // substantially (20-100x), often up to 60s. This can be solved by use of local catalogs, ie. // putenv("XML_CATALOG_FILES=/path/to/catalog.ent"); // // see: http://www.whump.com/moreLikeThis/link/03815 $xmlDOM->recover = true; $xmlDOM->substituteEntities = true; $xmlDOM->resolveExternals = true; // Load the XML based on its type switch ($xmlType) { case XSL_TRANSFORMER_DOCTYPE_FILE: $xmlDOM->load($xml); break; case XSL_TRANSFORMER_DOCTYPE_STRING: $xmlDOM->loadXML($xml); break; default: assert(false); } } // Prepare the XSL DOM if ($xslType == XSL_TRANSFORMER_DOCTYPE_DOM) { // We already have a DOM document, no need to create one assert(is_a($xsl, 'DOMDocument')); $xslDOM =& $xsl; } else { // Instantiate the XSL DOM document $xslDOM = new DOMDocument('1.0', XSLT_PROCESSOR_ENCODING); // Load the XSL based on its type switch ($xslType) { case XSL_TRANSFORMER_DOCTYPE_FILE: $xslDOM->load($xsl); break; case XSL_TRANSFORMER_DOCTYPE_STRING: $xslDOM->loadXML($xsl); break; default: assert(false); } } // Create and configure the XSL processor $processor = new XSLTProcessor(); // Register PHP functions if requested. // NB: This can open potential security issues; see FAQ/README if ($this->registerPHPFunctions) { $processor->registerPHPFunctions($this->registerPHPFunctions); } // Set XSL parameters (if any) if (is_array($this->parameters)) { foreach ($this->parameters as $param => $value) { $processor->setParameter(null, $param, $value); } } // Import the style sheet $processor->importStylesheet($xslDOM); // Process depending on the requested result type switch ($resultType) { case XSL_TRANSFORMER_DOCTYPE_STRING: $resultXML = $processor->transformToXML($xmlDOM); return $resultXML; case XSL_TRANSFORMER_DOCTYPE_DOM: $resultDOM = $processor->transformToDoc($xmlDOM); return $resultDOM; default: assert(false); } }
$options = getopt("o:", $longopts); $xml_fn = $options["xml"]; $xsl_fn = $options["xsl"]; $out_fn = isset($options["output"]) ? $options["output"] : $options["o"]; $css_fn = $options["css"]; $html_fn = isset($options["html"]) ? $options["html"] : NULL; // Load source documents $xml = new DOMDocument(); $xml->load($xml_fn); $xsl = new DOMDocument(); $xsl->load($xsl_fn); // Initialize and configure XSLT processor $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); error_log("XML -> HTML ..."); $html = $proc->transformToDoc($xml); // Save intermediate HTML (optional) if (isset($html_fn)) { $html->save($html_fn); } $html = $html->saveHTML(); error_log("... done"); // REMINDER: always import external stylsheets, otherwise mPDF is extremely slow $css = file_get_contents($css_fn); // external css error_log("HTML -> PDF ..."); $mpdf = new mPDF(); // PDF/A1-b compliance $mpdf->PDFA = true; // Convert HTML to PDF with CSS stylesheet $mpdf->WriteHTML($css, 1);
/** * Creates the Sig model DomDocument from WSDL2.0 DomDocument. * @param DomDocument $wsdl_dom WSDL2.0 DomDocument * @return DomDocument Sig model DomDocument */ function wsf_get_sig_model_dom(DomDocument $wsdl_dom) { require_once 'wsf_wsdl_consts.php'; $xslt_dom = new DOMDocument(); $xsl = new XSLTProcessor(); $xslt_str = file_get_contents(WSF_SIG_XSL_LOCATION, TRUE); if ($xslt_str && $xslt_dom->loadXML($xslt_str)) { $xsl->importStyleSheet($xslt_dom); $sig = $xsl->transformToDoc($wsdl_dom); return $sig; } else { return NULL; } }
/** * Atom 0.3 を RSS 1.0 に変換する(PHP5, DOM & XSL) */ function atom_to_rss_by_xsl($input, $stylesheet, $output) { $xmlDoc = new DomDocument(); if ($xmlDoc->load(realpath($input))) { $xslDoc = new DomDocument(); $xslDoc->load(realpath($stylesheet)); $proc = new XSLTProcessor(); $proc->importStyleSheet($xslDoc); $rssDoc = $proc->transformToDoc($xmlDoc); $rssDoc->save($output); $rss_content = FileCtl::file_read_contents($output); } else { $rss_content = null; } if (!$rss_content) { P2Util::pushInfoHtml('<p>p2 error: XSL - AtomをRSSに変換できませんでした。</p>'); return FALSE; } return $rss_content; }
/** * Harvest all available documents. * * @return string[] Array of MARCXML records * @throws Exception */ public function harvest() { $xml = $this->callXServer(['op' => 'login_request', 'user_name' => $this->username, 'user_password' => $this->password]); $doc = simplexml_load_string($xml); if (isset($doc->login_response->local_error)) { $this->_message("X-Server login failed: \n" . $xml, false, Logger::FATAL); throw new Exception("X-Server login failed"); } if (!isset($doc->login_response->auth)) { $this->_message("Could not find auth information in X-Server login response: \n" . $xml, false, Logger::FATAL); throw new Exception("X-Server login response missing auth information"); } if ((string) $doc->login_response->auth != 'Y') { $this->_message("X-Server login failed for '{$this->username}'", false, Logger::FATAL); throw new Exception("X-Server login failed"); } $session = (string) $doc->login_response->session_id; $xml = $this->callXServer(['op' => 'source_locate_request', 'session_id' => $session, 'locate_command' => $this->query, 'source_full_info_flag' => 'Y']); $style = new DOMDocument(); if ($style->load($this->basePath . '/transformations/strip_namespaces.xsl') === false) { throw new Exception('Could not load ' . $this->basePath . '/transformations/strip_namespaces.xsl'); } $doc = new DOMDocument(); if (!$doc->loadXML($xml)) { $this->_message("Failed to parse X-Server source locate response: \n" . $xml, false, Logger::FATAL); throw new Exception("Failed to parse X-Server source locate response"); } $responseNode = $doc->getElementsByTagName('source_locate_response'); if ($responseNode->length > 0) { $responseNode = $responseNode->item(0)->getElementsByTagName('local_error'); if ($responseNode->length > 0) { $this->_message("X-Server source locate request failed: \n" . $xml, false, Logger::FATAL); throw new Exception("X-Server source locate request failed"); } } $transformation = new XSLTProcessor(); $transformation->importStylesheet($style); $splitter = new FileSplitter($transformation->transformToDoc($doc), '//source_locate_response/source_full_info/record', ''); $records = []; while (!$splitter->getEOF()) { $oaiID = ''; $records[] = $splitter->getNextRecord($oaiID); } return $records; }