加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

XSLT:将标记的所有属性传递给php函数

发布时间:2020-12-13 16:13:36 所属栏目:PHP教程 来源:网络整理
导读:我编写了以下XSLT模板: xsl:template match="foo:*" xsl:processing-instruction name="php"$s = ob_get_clean(); ob_start(); $this-callExtensionStartHandler('xsl:value-of select="local-name()" /');/xsl:processing-instruction xsl:apply-templates
我编写了以下XSLT模板:

<xsl:template match="foo:*">
    <xsl:processing-instruction name="php">$s = ob_get_clean(); ob_start(); $this->callExtensionStartHandler('<xsl:value-of select="local-name()" />');</xsl:processing-instruction>
    <xsl:apply-templates/>
    <xsl:processing-instruction name="php">$sExtensionContent = ob_get_clean(); ob_start(); echo $s; echo $this->callExtensionEndHandler('<xsl:value-of select="local-name()" />',$sExtensionContent);</xsl:processing-instruction>
</xsl:template>

现在我想将标签的所有属性及其值传递给php函数.如果我有一个模板:

<foo:test id="a" bar="xzz"/>

我想在我的php函数中有一个数组(‘id’=>’a’,’bar’=>’xzz’).那可能吗.我不想限制属性的名称,因此可以有任何属性名称.

解决方法

我不熟悉PHP,但这可能会有所帮助:

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

 <xsl:template match="foo:test">
  array(<xsl:apply-templates select="@*"/>)
 </xsl:template>

 <xsl:template match="foo:test/@*">
  <xsl:if test="not(position()=1)">,</xsl:if>
  <xsl:value-of select=
  'concat(&quot;&apos;&quot;,name(),&quot;&apos;&quot;," => ",.,&quot;&apos;&quot;)'/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于此XML文档(提供的文档,格式良好)时:

<foo:test id="a" bar="xzz" xmlns:foo="foo:foo"/>

产生了想要的正确结果:

array('id' => 'a','bar' => 'xzz')

更新:OP在评论中询问:

Thank you,that looks great! Is it possible to add an escaping to the
attribute value? Every ‘ should become ’

答:是的,我们可以通过略微修改原始解决方案来获得此输出:

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

 <xsl:template match="foo:test">
  array(<xsl:apply-templates select="@*"/>)
 </xsl:template>

 <xsl:template match="foo:test/@*">
  <xsl:if test="not(position()=1)">,</xsl:if>
  <xsl:value-of select=
  'concat(&quot;&;quot;,&quot;&;quot;,&quot;&apos;&quot;)'/>
 </xsl:template>
</xsl:stylesheet>

当应用于同一XML文档时,此转换将生成:

array('id' => 'a','bar' => 'xzz')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读