SimpleXML Xpath query and transformToXML


SimpleXML Xpath query and transformToXML

我有一个XML文档,我试图用xpath查询它,然后通过XSLTProcessor运行生成的节点。xpath查询运行良好,但我不知道如何将SimpleXMLElement与XSLTProcessor一起使用。如有任何帮助,我们将不胜感激。

$data = simplexml_load_file('document.xml');
$xml = $data->xpath('/nodes/node[1]');
$processor = new XSLTProcessor;
$xsl = simplexml_load_file('template.xsl');
$processor->importStyleSheet($xsl);
echo '<div>'.$processor->transformToXML($xml).'</div>';

XML:

<nodes>
    <node id="5">
        <title>Title</title>
    </node>
</nodes>

XSL:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//node">
<xsl:value-of select="@id" />
<xsl:value-of select="title" />
...

我认为不能将$xml传递给XSLTProcessor::transformToXML方法,因为它是数组(由SimpleXMLElement::xpath生成):

PHP警告:XSLTProcessor::transformToXml()期望参数1是对象,上的/var/www/index.php中给出的数组11号线

简单的补救方法是将XPath表达式放入XSL样式表:

<xsl:output method="html"/> <!-- don't embed XML declaration -->
<xsl:template match="/nodes/node[1]">
    <xsl:value-of select="@id"/>
    <xsl:value-of select="title"/>
</xsl:template>

和:

$xml = simplexml_load_file('document.xml');
$xsl = simplexml_load_file('template.xsl');
$xslt = new XSLTProcessor;
$xslt->importStyleSheet($xsl);
echo '<div>'.$xslt->transformToXML($xml).'</div>';

编辑:

另一种方法是在XSL转换中只使用数组的第一个元素(确保它不是null):

$data = simplexml_load_file('document.xml');
$xpath = $data->xpath('/nodes/node[1]');
$xml = $xpath[0];
$xsl = simplexml_load_file('template.xsl');
$xslt = new XSLTProcessor;
$xslt->importStyleSheet($xsl);
echo '<div>'.$xslt->transformToXML($xml).'</div>';

和:

<xsl:template match="node">
    <xsl:value-of select="@id"/>
    <xsl:value-of select="title"/>
</xsl:template>