开发者

SimpleXML Xpath query and transformToXML

I have an XML document, which I'm trying to query with xpath and then run the resulting node through an XSLTProcessor. The xpath query works fine, but I can't figure out how to use the SimpleXMLElement with XSLTProcessor. Any help would be appreciated.

$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" />
...


I think that you can't pass that $xml to XSLTProcessor::transformToXML method, because it's array (produced by SimpleXMLElement::xpath):

PHP Warning: XSLTProcessor::transformToXml() expects parameter 1 to be object, array given in /var/www/index.php on line 11

Simple remedy for that is to just put XPath expression into XSL stylesheet:

<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>

and:

$xml = simplexml_load_file('document.xml');
$xsl = simplexml_load_file('template.xsl');

$xslt = new XSLTProcessor;
$xslt->importStyleSheet($xsl);

echo '<div>'.$xslt->transformToXML($xml).'</div>';

EDIT:

Another way is to just use first element of array in XSL transform (make sure it's not 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>';

and:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜