使用PHP / XSL基于ID生成XML页面

时间:2014-09-12 14:25:33

标签: php xml xslt

我正在构建一个小型网站,该网站使用catalog.xml作为对象列表。我还有menu.xml和footer.xml文件。

我想根据页面URL中的对象ID为catalog.xml中的每个对象生成一个单独的页面。

我能够使用此代码来实现它:

<?php
$goods = simplexml_load_file('catalog/catalog.xml');
if(isset($_GET['id'])) {
foreach($goods as $id => $item) {
if(!($item->attributes()->id == $_GET['id'])) {
  continue;
}

$xslt = new xsltProcessor;

$xsl = new domDocument;
$xsl->load('item.xsl');
$xslt->importStyleSheet($xsl);

$xml = new domDocument;
$xml->loadXML($item->asXML());

print $xslt->transformToXML($xml);
exit;
}
} else {
$xslt = new xsltProcessor;

$xsl = new domDocument;
$xsl->load('item.xsl');
$xslt->importStyleSheet($xsl);

$xml = new domDocument;
$xml->loadXML($items->asXML());

print $xslt->transformToXML($xml);
}

目录XML示例:

<goods>
    <item type="shampoo" id="0001">
    <title>Object name</title>
    <brand>Dodo</brand>
    <weight>226,6</weight>
    <country>Germany</country>
    <price>34</price>
    <description/> 
    <thumb>image.jpg</thumb>
    <photo></photo>
    </item>
</goods>

唯一的问题是这里没有提到menu.xml和footer.xml。

我有item.xml文件,我想用它来生成对象页面:

<page>
    <head><header href="head.xml"/></head>
    <content><catalog href="catalog/catalog.xml"/></content>
    <foot><footer href="footer.xml"/></foot>
</page>

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

当item.xsl处理项目记录时,它还可以通过document()函数引用item.xml。

我将举例说明一种只尝试从header.xml中提取页眉和页脚名称的简单方法。您可以添加更复杂的逻辑来处理item.xml的每个节点。

<xsl:template match="/">
  <page>
    <head>
      <xsl:variable name="head" select="document('item.xml')/page/head/header/@href"/>
      <xsl:copy-of select="document($head)/*"/>

      <!--process the actual input content sent to the stylesheet-->
      <content><xsl:apply-templates select="*"></content>

      <xsl:variable name="foot" select="document('item.xml')/page/foot/footer/@href"/>
      <xsl:copy-of select="document($foot)/*"/>
    </head>
  </page>
</xsl:template>

更复杂的方法:如果您确实需要使用样式表处理item.xml文件,则可以执行以下操作。

<xsl:apply-templates select="document('item.xml')/*">
  <xsl:with-param name="catalog-item" select="."/>
</xsl:apply-templates>
祝你好运!