如何将XSLT函数与PHP5一起使用


How can I use XSLT functions with PHP5?

最近,我一直在帮助某人将网站从一个远程Web服务器转移到本地Web服务器。然而,我继承的代码包含这样的代码:

$xsltproc = xslt_create();
$html = xslt_process($xsltproc, $path, 'xsl/Stylesheet2.xsl');

然而,PHP5不喜欢这样的代码,而且从我所读到的内容来看,在PHP5中不允许使用上面这样的XSLT函数。显然,这段代码一定是用PHP4编写的,并在运行PHP4的服务器上使用。我的问题是,如何让这些代码在我的PHP5服务器上工作(还有很多使用"XSLT"的代码,上面只是一个片段)?重写所有代码是使其工作的唯一方法吗?如果可能的话,我宁愿避免。

我希望它能解决你的问题

function transform($xmlvalue, $xsl,$paraArray=array(),$IsFileXML=FALSE)
        {
            $XML = new DOMDocument();
            if ($IsFileXML)
                $XML->load( $xmlvalue);
            else
                $XML->loadXML( $xmlvalue );
            $xslt = new XSLTProcessor();
            $XSL = new DOMDocument();
            $XSL->load( $xsl, LIBXML_NOCDATA);
            $xslt->importStylesheet( $XSL );
            foreach ($paraArray as $key => $value) {
                $xslt->setParameter('', $key,$value);
            }
            $xslt->registerPHPFunctions();
            return $xslt->transformToXML( $XML );
        }

你必须像这个一样调用xslt中的php函数

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:php="http://php.net/xsl"  exclude-result-prefixes="php" version="1.0">
  <xsl:output method="html" version="1.0" encoding="utf-8" indent="yes"  omit-xml-declaration="no"/>
.....
.....
....
<tr>
              <td valign="top" class="found_on">
                Added : <strong>
                  <xsl:value-of select ="php:function('ClsXSLTFunction::getPublishDate',$publishdate)"/>
                </strong> by <strong>
                  <xsl:value-of select="user"/>
                </strong>
              </td>
            </tr>
....
....
</xsl:stylesheet>

您也可以在xslt中调用自己的函数,但您必须创建一个具有静态函数的类,如

class ClsXSLTFunction
{
    public static function getPublishDuration($publishdate)
    {
        $epoch_1 = strtotime($publishdate);
        $epoch_2 = strtotime(date('y-m-d H:m:s'));
        $diff_seconds  = $epoch_1 - $epoch_2;
        $diff_weeks    = floor($diff_seconds/604800);
        $diff_seconds -= $diff_weeks   * 604800;
        $diff_days     = floor($diff_seconds/86400);
        $diff_seconds -= $diff_days    * 86400;
        $diff_hours    = floor($diff_seconds/3600);
        $diff_seconds -= $diff_hours   * 3600;
        $diff_minutes  = floor($diff_seconds/60);
        $diff_seconds -= $diff_minutes * 60;
        return $diff_days."d".$diff_hours."h".$diff_minutes."m";
    }
    public static function getPublishDate($publishdate)
    {
        return date("m/d/Y",strtotime($publishdate));
    }
}