我已经编写了以下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')。有没有可能。我不想限制属性的名称,所以可以有任何属性名称。
发布于 2011-10-07 13:21:30
我不熟悉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("'",name(),"'",
" => ",
"'",.,"'")'/>
</xsl:template>
</xsl:stylesheet>在此文档(所提供的文档格式良好)上应用此转换时:
<foo:test id="a" bar="xzz" xmlns:foo="foo:foo"/>生成所需的正确结果
array('id' => 'a', 'bar' => 'xzz')更新:在评论中,操作员询问:
谢谢你,看起来很棒!是否可以向属性值添加转义?每一个“应该成为\”
Answer:可以,我们可以通过稍微修改原始解决方案来获得以下输出:
<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("\","'",name(),"\","'",
" => ",
"\","'",.,"\","'")'/>
</xsl:template>
</xsl:stylesheet>当应用于同一文档时,此转换将生成
array(\'id\' => \'a\', \'bar\' => \'xzz\')发布于 2011-10-07 02:51:57
难道不能只传递元素本身,然后使用适当的php函数获取所有属性吗?这样您就不需要关心属性的名称了,因为我确信有一种方法可以遍历php中元素的所有属性:)
https://stackoverflow.com/questions/7678653
复制相似问题