PHP - XSLTProcessor::transformToXml() 函式



定義和用法

XML 是一種用於在網路上共享資料的標記語言,XML 既可供人類閱讀,也可供機器讀取。XSL 擴充套件是 XSL 標準的實現,用於使用 libxslt 庫執行 XSTL 轉換。

XSLTProcessor::transformToXml() 函式接受 DOMNode 類的物件作為引數,並透過應用樣式表將其轉換為字串。

語法

XSLTProcessor::transformToXml($doc);

引數

序號 引數和說明
1

doc(必填)

這是 DOMNode 類的一個物件,表示要轉換的文件。

返回值

如果成功,此函式返回一個字串值,表示轉換的結果;如果失敗,則返回一個布林值 FALSE。

PHP 版本

此函式首次引入 PHP 5 版本,並在所有後續版本中均有效。

示例

以下是此函式的示例:

sample.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<Tutorial>
   <Title>JavaFX</Title>
   <Authors>
      <Author>Krishna</Author>
      <Author>Rajeev</Author>
   </Authors>
   <Body>Sample text</Body>
</Tutorial>

sample.xsl

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="text"/>

   <xsl:template match="/">
      Title - <xsl:value-of select="/Tutorial/Title"/>
      Authors: <xsl:apply-templates select="/Tutorial/Authors/Author"/>
   </xsl:template>

   <xsl:template match="Author">
      - <xsl:value-of select="." />
   </xsl:template>
</xsl:stylesheet>

sample.php

<?php
   //Loading an XSL document
   $xsl = new DOMDocument();
   $xsl->load("sample.xsl");

   //Loading an XML document
   $xml = new DOMDocument();
   $xml->load("sample.xml");

   //Creating an XSLTProcessor
   $proc = new XSLTProcessor();

   //Importing the XSL document
   $proc->importStyleSheet($xsl);

   //Transforming the style to XML
   $res = $proc->transformToXml($xml);
   print($res);
?>

這將產生以下結果:

Title - JavaFX
   Authors:
   - Krishna
   - Rajeev
php_function_reference.htm
廣告