<?php

// Include the getConfig and file_get_contents functions used for data retrieval.

include('includes/functions.php');

// This if statment is purely for the purposes of giving the user the option to read the KML file within the browser, if the view get variable is set to true.

if(!isset($_GET['view'])) {
    
header("Content-type: application/vnd.google-earth.kml+xml");  //set the content type to that for KML 
}

function 
station_to_kml($station){
// Transform a station XML object to a KML string 

    // Get the XML data from the weather station passed to the function.

    
$data file_get_contents($station->base);
    
    
// Create XML object from XML data pulled in.
    
    
$xml = new simpleXMLElement($data);
    
    
// Convert the rfc822 time provided in the feed into GMT and display as 12 hour clock with minutes and am/pm.
    
    
$time gmdate('g:ia'strtotime($xml->observation_time_rfc822));

    
// Add units onto the appropriate variables.
    
    
if($xml->temp_c=='NA'$temp 'N/A'; else $temp $xml->temp_c.'&deg;C';
    if(
$xml->windchill_c=='NA'$chill 'N/A'; else $chill $xml->windchill_c.'&deg;C';
    if(
$xml->wind_mph=='NA'$mph 'N/A'; else $mph $xml->wind_mph.'mph';

// CDATA is used here to embed the html as plain characters rather then XML
  
return <<<EOT
<Placemark>
    <name>
{$station->title}</name>
    <description>
      <![CDATA[
                <img src="
{$xml->icon_url_base}{$xml->icon_url_name}" style="float: right; width: 55px; height: 58px;" alt="{$xml->image->title}" />
                <a href="
{$station->home}">Live Weather</a><br />
                Weather: 
{$xml->weather}<br />
                Temperature: 
{$temp}<br />
                Wind Chill: 
{$chill}<br />
                Wind Direction: 
{$xml->wind_dir}<br />
                Wind Speed: 
{$mph}<br />
                Last Updated: 
{$time}
      ]]>
    </description>
    <Point>
       <coordinates>
{$station->longitude},{$station->latitude},0</coordinates>
    </Point>
</Placemark>
EOT;
};

// Retrieve the XML config file.

$config getConfig();
    
echo 
'<?xml version="1.0" encoding="UTF-8"?>';
?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
  <name><?=$config->title?></name>
        <?php
          
foreach ($config->weather->station as $station//iterate through the stations in the configuration file
            
echo station_to_kml($station);   // convert each one to a piece of kml and output 
        
?>
  </Document>
</kml>