Friday, 12 September 2014

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



I am building a small website that uses a catalog.xml for a list of objects. I also have menu.xml and footer.xml files.


I want to generate a separate page for each object from catalog.xml based on the object ID from page URL.


I was able to party achieve it using this code:



<?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);
}

Example of catalog 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>


The only problem is that menu.xml and footer.xml are not icluded here.


I have item.xml file that I'd like to use for generating the object page:



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


What is the best way to accomplish that?


No comments:

Post a Comment