繁体   English   中英

使用PHP / XSL根据ID从XML生成页面

[英]Generate pages from XML based on ID's using PHP/XSL

我正在建立一个使用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>

做到这一点的最佳方法是什么?

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

我将说明一种简单的方法,该方法仅尝试将页眉和页脚名称从item.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>

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM