略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: XSLTProcessor::transformToDoc

2025-02-27

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDocTransform to a document

说明

public XSLTProcessor::transformToDoc(object $document, ?string $returnClass = null): object|false

Transforms the source node to a document (e.g. DOMDocument) applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

参数

document

The Dom\Document, DOMDocument, SimpleXMLElement or libxml-compatible object to be transformed.

returnClass

This optional parameter may be used so that XSLTProcessor::transformToDoc() will return an object of the specified class. That class should either extend or be the same class as document's class.

错误/异常

The following errors are possible when using an expression that invokes PHP callbacks.

  • Throws an Error if a PHP callback is invoked but there were no callbacks registered, or if the named callback was not registered.
  • Throws a TypeError if the php:function syntax is used and the handler name is not a string.
  • Throws an Error if a non-DOM object was returned from a callback.

返回值

The resulting document or false on error.

更新日志

版本 说明
8.4.0 Now throws an Error if the callback cannot be invoked, instead of emitting a warning.
8.4.0 Added support for Dom\Document.

示例

示例 #1 Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

以上示例会输出:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

示例 #2 Transforming to a Dom\Document

<?php

$xml
= Dom\XMLDocument::createFromFile('collection.xml');
$xsl = Dom\XMLDocument::createFromFile('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

以上示例会输出:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

参见

添加备注

用户贡献的备注 1 note

up
1
franp at free dot fr
18 years ago
In most cases if you expect XML (or XHTML) as output you better use transformToXML() directly. You gain better control over xsl:output attributes, notably omit-xml-declaration.

Instead of :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

do use :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

In the first case, <?xml version="1.0" encoding="utf-8"?> is added whatever you set the omit-xml-declaration while transformToXML() take the attribute into account.

官方地址:https://www.php.net/manual/en/xsltprocessor.transformtodoc.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3