将变量传递给XSLT

4 php xml xslt

我是XML/XSL的新手.我希望能够在规则字符串中传递var并返回正确的数据.

现在我有这个PHP:

<?php
$params = array('id' => $_GET['id']);

$xslDoc = new DOMDocument(); 
$xslDoc->load("test.xsl"); 

$xmlDoc = new DOMDocument(); 
$xmlDoc->load("test.xml");

$xsltProcessor = new XSLTProcessor(); 
$xsltProcessor->registerPHPFunctions(); 
$xsltProcessor->importStyleSheet($xslDoc); 

foreach ($params as $key => $val)
    $xsltProcessor->setParameter('', $key, $val);

echo $xsltProcessor->transformToXML($xmlDoc);
?>
Run Code Online (Sandbox Code Playgroud)

我的xml文件如下所示:

<Profiles> 
  <Profile> 
    <id>1</id> 
    <name>john doe</name> 
    <dob>188677800</dob> 
  </Profile> 
  <Profile> 
    <id>2</id> 
    <name>mark antony</name> 
    <dob>79900200</dob> 
  </Profile> 
  <Profile> 
    <id>3</id> 
    <name>neo anderson</name> 
    <dob>240431400</dob> 
  </Profile> 
  <Profile> 
    <id>4</id> 
    <name>mark twain</name> 
    <dob>340431400</dob> 
  </Profile> 
  <Profile> 
    <id>5</id> 
    <name>frank hardy</name> 
    <dob>390431400</dob> 
  </Profile> 
</Profiles> 
Run Code Online (Sandbox Code Playgroud)

我的xsl看起来像这样

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="id" />

  <xsl:template match="*">
    <html><body>
    <h2>Profile</h2>
    <table cellspacing="1" cellpadding="5" border="1"> 
      <caption>User Profiles</caption> 
      <tr><th>ID</th><th>Name</th><th>Date of Birth</th></tr> 

      <xsl:for-each select="/Profiles/Profile[id='$id']">
        <tr> 
          <td><xsl:value-of select="id"/></td> 
          <td><xsl:value-of select="php:function('ucwords', string(name))"/></td> 
          <td><xsl:value-of select="php:function('date', 'jS M, Y', number(dob))"/></td> 
        </tr> 
      </xsl:for-each> 
    </table> 
    </body></html>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当我像这样测试网址时:

http://foo.com/sanbox/index.php?id=2

我只得到:

Profile
User Profiles ID    Name    Date of Birth.

PQW*_*PQW 7

该错误是因为您没有包含正确的命名空间.

在你的xsl:stylesheet声明中包含xmlns:php ="http://php.net/xsl"

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl"
>
Run Code Online (Sandbox Code Playgroud)