tags:

views:

34

answers:

2

I have a PHP script that caches a remote XML file. I want to XSL transform it before caching, but don't know how to do this:

<?php

   // Set this to your link Id

   $linkId = "0oiy8Plr697u3puyJy9VTUWfPrCEvEgJR";

   // Set this to a directory that has write permissions

   // for this script

   $cacheDir = "temp/";

   $cachetime = 15 * 60; // 15 minutes

   // Do not change anything below this line

   // unless you are absolutely sure

   $feedUrl="http://mydomain.com/messageService/guestlinkservlet?glId=";

   $cachefile = $cacheDir .$linkId.".xml";

   header('Content-type: text/xml');

   // Send from the cache if $cachetime is not exceeded

   if (file_exists($cachefile) && (time() - $cachetime

      < filemtime($cachefile)))

   {

      include($cachefile);
      echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->\n";
      exit;

   }

   $contents = file_get_contents($feedUrl . $linkId);

   // show the contents of the XML file

   echo $contents;

   // write it to the cache

   $fp = fopen($cachefile, 'w');

   fwrite($fp, $contents);

   fclose($fp);

?>

This is the XSL string I want to use to transform it:

<xsl:template match="/">
    <kml xmlns="http://www.opengis.net/kml/2.2"&gt;
        <Document>
            <xsl:apply-templates select="messageList" />
        </Document>
    </kml>
</xsl:template>

<xsl:template match="messageList">
    <name>My Generated KML</name>
    <xsl:apply-templates select="message" />
</xsl:template>

<xsl:template match="message">
    <Placemark>
        <name><xsl:value-of select="esnName" /></name>
        <Point>
            <coordinates>
                <xsl:value-of select="latitude" />,<xsl:value-of select="longitude" />
            </coordinates>
        </Point>
    </Placemark>
</xsl:template>

I want to actually transform XML input and save/return a KML format. Can someone please help adjust this script? This was given to me and I am a little new to it.

A: 

Use the XSL extension, there is an example here:

http://www.php.net/manual/en/book.xsl.php#90510

replace your file_get_contents call with:

$XML = new DOMDocument(); 
$XML->load( $feedUrl . $linkId ); 

/* 
this is the same as the example:
*/
$xslt = new XSLTProcessor(); 
$XSL = new DOMDocument(); 
$XSL->load( $xslFile ); 
$xslt->importStylesheet( $XSL ); 

then replace the "print" line with file_put_contents( $cachefile, $xslt->transformToXML( $XML ) );

Christopher W. Allen-Poole
+1  A: 
$domOrigin = new DOMDocument('1.0');
$domOrigin->loadXML($contents);

$domXsl = new DOMDocument('1.0');
$domXsl->load('/path/to/stylesheet.xsl',LIBXML_NOCDATA);

$processor = new XSLTProcessor();
$processor->importStylesheet($domXsl);

file_put_contents($cachfile, $processor->transformToXml($domOrigin)); 

Ill leave it to you to integrate that :-)

prodigitalson