【问题标题】:Pass URL as a parameter to XSL将 URL 作为参数传递给 XSL
【发布时间】:2014-09-13 18:17:08
【问题描述】:

我想将当前页面 URL 作为属性传递给 XSL 模板。据我了解,它应该作为参数传递,然后用作属性。

我使用 PHP 加载 XML & XSL 文件:

<?php
$xml = new DOMDocument;
$xml->load('main.xml');

$xsl = new DOMDocument;
$xsl->load('blocks/common.xsl');

$proc = new XSLTProcessor;

$proc->importStyleSheet($xsl);

echo $proc->transformToXML($xml);
?> 

例如,如何更改此代码以将 URL 作为名为“current-url”的参数传递?

我在这里看到了很多类似的问题,有不同的解决方案,但到目前为止没有一个对我有用。提前谢谢你。

【问题讨论】:

    标签: php xml url xslt parameters


    【解决方案1】:

    也许你已经尝试过这种方法,但如果没有:

    <?php
    
      $params = array('current-url' => $_SERVER['REQUEST_URI']);
    
      $xml = new DOMDocument;
      $xml->load('main.xml');
    
      $xsl = new DOMDocument;
      $xsl->load('blocks/common.xsl');
    
      $proc = new XSLTProcessor;
      $proc -> registerPHPFunctions();
      $proc->importStyleSheet($xsl);
    
      foreach ($params as $key => $val)
        $proc->setParameter('', $key, $val);
    
      echo $proc->transformToXML($xml);
      ?>
    

    在xsl中,在模板上方添加

    <xsl:param name="current-url" />
    

    在模板中,您可以使用

    <xsl:value-of select="$current-url" />
    

    如果还没有,您必须将xmlns:php="http://php.net/xsl" 添加到 xsl:stylesheet 声明中。
    供参考:registerPHPFunctions() 和您可能已经检查过的解决方案 SO:Passing variables to XSLT

    【讨论】:

    • 谢谢你 matthias_h。现在试过了,但我在第 28 行收到 Call to a member function setParameter() on a non-object,即 $xsltProcessor-&gt;setParameter('', $key, $val); 想不通,你有什么想法吗?
    • 刚刚更新了答案 - 出现复制/粘贴错误。它应该是 $proc->setParameter( ... 而不是 $xsltProcessor->setParameter (..
    猜你喜欢
    • 2012-11-03
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多