簡體   English   中英

PHP中的多個XML / XSLT文件,使用XSLT轉換一個文件並添加其他文件,但首先使用PHP處理它

[英]Multiple XML/XSLT files in PHP, transform one with XSLT and add others but process it first with PHP

我正在用PHP中的XSLT正確處理XML文件轉換。 實際上,我使用以下代碼:

$xml = new DOMDocument;
$xml->LoadXML($xml_contents);

$xsl = new DOMDocument;
$xsl->load($xsl_file);

$proc = new XSLTProcesoor;
$proc->importStyleSheet($xsl);

echo $proc->transformToXml($xml);

$xml_contents是用PHP處理的XML,方法是先包含XML文件,然后分配$xml_contents = ob_get_contents(); ob_end_clean(); $xml_contents = ob_get_contents(); ob_end_clean(); 這迫使在XML上處理PHP代碼,並且效果很好。

我的問題是我使用了多個XML文件,並且此XML文件上有需要處理的PHP代碼,並且具有關聯的XSLT文件來處理數據。 實際上,我將使用以下代碼將這些文件包含在XSLT中:

<!-- First I add the XML file -->
<xsl:param name="menu" select="document('menu.xml')" />

<!-- Next I add the transformations for menu.xml file -->
<xsl:include href="menu.xsl" />

<!-- Finally, I process it on the actual ("parent") XML -->
<xsl:apply-templates select="$menu/menu" />

我的問題是我該如何處理。 我需要將多個XML(+ XSLT)文件添加到將包含PHP的第一個XML文件中,因此需要對其進行處理。

先感謝您!

我不確定“將包含PHP的XML文件”是什么意思,但是我猜想在啟動XSLT之后,您需要php來干擾它。 否則,您將在運行任何XSLT轉換之前使用PHP來操縱源XML。

有php功能,雖然它是標准XSLT的擴展,但允許您在處理過程中在XSLT樣式表中運行任意php。

更多信息和示例

編輯:

第二種想法,如果您只需要指定要加載的XML而無需將其硬編碼到XSLT中,則document()函數可以使用源XML節點作為要加載的文件的名稱。 因此,您只需以XML生成名稱,然后讓document()讀取它們以在模板中進一步參考。

2種解決方案,也許其中一種可以。

未經測試,但是您可以在PHP中實現自定義流。

<?php

// define your custom stream, should process xslt
class CustomStream extends streamWrapper {
    // http://www.php.net/manual/en/class.streamwrapper.php
}

// declare your custom stream
stream_wrapper_register('extra', 'CustomStream');

// then load your preprocessed on the fly in your example.xsl
$xml_contents = <<<EOF
...
<xsl:param name="menu" select="document('extra://menu.xml')" />
EOF;


?>

解決方案n°2,在您的xslt中注冊php函數,並使用它:

<?php
// declare your function
// see http://www.php.net/manual/fr/xsltprocessor.registerphpfunctions.php
function resolve($xml_contents, $xsl_file=null) {
    $dom = new DomDocument;
    $dom->loadXML($xml_contents);
    if ($xsl == null) {
        return $dom;
    }

    $xsl = new DOMDocument;
    $xsl->load($xsl_file);

    $proc = new XSLTProcessor;

    $proc->registerPHPFunctions('resolve');
    $proc->importStyleSheet($xsl);

    return $proc->transformToDoc($xml_contents);
}


// then handle your master xsl
$xsl_contents = <<<EOF
...
<xsl:param name="menu" select="php:function('resolve', 'menu.xml', 'menu.xsl')" />
EOF;

$dom = new DomDocument;
$dom->loadXML($xml_contents);

$xsl = new DOMDocument;
$xsl->loadXML($xsl_contents);

$proc = new XSLTProcessor;

$proc->registerPHPFunctions('resolve');
$proc->importStyleSheet($xsl);

return $proc->transformToDoc($xml_contents);

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM