2024 日本 PHP 研討會

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc轉換為文件

描述

公開 XSLTProcessor::transformToDoc(物件 $document, ?字串 $returnClass = null): 物件|false

使用 XSLTProcessor::importStylesheet() 方法所提供的樣式表,將來源節點轉換為文件(例如 DOMDocument)。

參數

document

要轉換的 DOMDocumentSimpleXMLElement 或與 libxml 相容的物件。

returnClass

此選用參數可用於讓 XSLTProcessor::transformToDoc() 返回指定類別的物件。該類別應繼承或與 document 的類別相同。

返回值

產生的文件,或錯誤時返回 false

範例

範例 #1 轉換為 DOMDocument

<?php

// 載入 XML 來源
$xml = new DOMDocument;
$xml->load('collection.xml');

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

// 設定轉換器
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // 附加 xsl 規則

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

?>

以上範例將輸出

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

參見

新增註記

使用者貢獻的註記 1 則註記

franp at free dot fr
18 年前
大多數情況下,如果您期望輸出 XML(或 XHTML),最好直接使用 transformToXML()。您可以更好地控制 xsl:output 屬性,尤其是 omit-xml-declaration。

不要使用
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

而是使用
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

在第一種情況下,無論您如何設定 omit-xml-declaration 屬性,都會新增 <?xml version="1.0" encoding="utf-8"?>,而 transformToXML() 會考慮該屬性。
To Top