php - 在 xpath 选择返回的 SimpleXMLElements 上使用 TransformToXml

标签 php xslt simplexml

我希望能够使用 XSLT 来处理由 XPath 选择的 XML 片段。当我传递 $xmlSnippet 时,它的行为就像我传递了整个 $xml 一样。我如何告诉处理器处理片段而不是整个文件?

XML

<?xml version="1.0" encoding="UTF-16"?>
<FMPReport link="Summary.xml" creationTime="12:10:13 pm" creationDate="30/10/2015" type="Report" version="14.0.3">
<File name="assets.fmp12" path="server.com">
<CustomFunctionCatalog>
    <CustomFunction id="1" functionArity="1" visible="True" parameters="pageID" name="!filemakerstandards.org">
        <Calculation><![CDATA["http://filemakerstandards.org/pages/viewpage.action?pageId=" & pageID]]></Calculation>
    </CustomFunction>
    <CustomFunction id="2" functionArity="2" visible="True" parameters="name;value" name="#">
        <Calculation><![CDATA['example 2']]></Calculation>
    </CustomFunction>
</CustomFunctionCatalog>
</File>
</FMPReport>

XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" encoding="UTF-8"/>
    <xsl:template match="/">
        <xsl:value-of select="name(child::*[1])"/>
        </xsl:template>
    <xsl:template match="text()" />
</xsl:stylesheet>

PHP

function displayCustomFunction($customFunctionId) {
    LIBXML_NOWARNING;
    LIBXML_NOCDATA;
    LIBXML_PARSEHUGE;
    LIBXML_BIGLINES;
    LIBXML_COMPACT;
    $filePath = 'xml/abc';
    $xslPath = 'xsl/abc';
    $xml = simplexml_load_file( $filePath, 'SimpleXMLElement');
    // ->xpath returns an array, in this case, an array of one item. array()[0] will be a SimpleXMLElement
    $xmlSnippet  = $xml->xpath('File/CustomFunctionCatalog/CustomFunction[@id=\''.$customFunctionId.'\']')[0];
    $xsl = simplexml_load_file( $xslPath, 'SimpleXMLElement');
    $xslt = new XSLTProcessor();
    $xslt->importStylesheet($xsl);
    $xslt->transformToXml($xml);        // returns 'FMPReport'
    $xslt->transformToXml($xmlSnippet); // returns 'FMPReport'. Expecting 'Calculation'
}

最佳答案

没有得到任何答案 我只是通过构建一个字符串并将其作为 XML 加载来解决这个问题。

$cfString = '';
foreach( $cfArray as $item){
    $cfString .= $item->asXML();
}

$cfXml = <<<XML
<?xml version='1.0'?> 
<FMPReport>
<File name="{$fileName[0]}">
<CustomFunctionCatalog>
$cfString
</CustomFunctionCatalog>
</File>
</FMPReport>
XML;

$xml  = simplexml_load_string($cfXml);

然后使用 XSLT 进行处理。

关于php - 在 xpath 选择返回的 SimpleXMLElements 上使用 TransformToXml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256697/

相关文章:

php - 检查文件名是否包含php中的变音符号

php - N 层树 PHP MYSQL 帮助

PHP字符串拆分问题

SimpleXML对象的PHP、json_encode、json_decode

php - 访问 SimpleXMLElement 中的数字属性

php - 有没有办法通过节点名称获取简单的 XML 子元素?

php - PHP 有比 int 大的数据类型吗?

xslt - 如何从一堆变量中选择最小值?

Java 和 XSLT : How to specify multiple input files to xslt in java?

XSLT 命名空间问题