2014-09-12 56 views
0

我正在構建一個使用catalog.xml作爲對象列表的小網站。我也有menu.xml和footer.xml文件。使用PHP/XSL從基於ID的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這裏沒有icluded 。

我有我想要用於生成對象頁item.xml文件:

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

什麼是實現這一目標的最佳途徑?

回答

0

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

祝你好運!

+0

謝謝,這部分爲我工作。但是由於我使用的是自定義xsl框架,它似乎與此設置相沖突。將進一步挖掘。我想知道是否有更好的方法根據URL中傳遞的ID從catalog.xml中選擇節點。 – 2014-09-13 16:17:03