Skip to content

Instantly share code, notes, and snippets.

@smulube
Created October 30, 2012 09:59
Show Gist options
  • Save smulube/3979372 to your computer and use it in GitHub Desktop.
Save smulube/3979372 to your computer and use it in GitHub Desktop.
Simple PHP script for converting WEL web energy logger XML for Cosm
<?
// set some variables we'll use later
$timezone_offset = '-05'; // set to your local timezone offset from UTC
$raw_url = "http://urltoyourdata.xml"; // replace with actual path to your published raw data
$title = "The title for your feed"; // the title for your Cosm feed
// Get raw data
$raw_xml = simplexml_load_file($raw_url);
// Extract timestamp. Note all this messing about is to create an ISO8601
// formatted string in the correct time zone, as this is what Cosm expects
$date_part = $raw_xml->xpath('/Devices/Device[@Name="Date"]');
$time_part = $raw_xml->xpath('/Devices/Device[@Name="Time"]');
$timestamp = strtotime($date_part[0]['Value'] . $time_part[0]['Value']);
$iso8601_timestamp = strftime('%Y-%m-%dT%H:%M:%S' . $timezone_offset, $timestamp);
// Construct xml for Cosm
$cosm_xml = new SimpleXMLElement('<eeml/>');
$cosm_xml->addAttribute('xmlns', 'http://www.eeml.org/xsd/0.5.1');
$cosm_xml->addAttribute('version', '0.5.1');
$environment = $cosm_xml->addChild('environment');
$environment->addChild('title', $title);
foreach ($raw_xml->Device as $device) {
// Don't publish Date/Time as separate datastreams
if($device['Name'] == 'Date' || $device['Name'] == 'Time') {
continue;
}
$datastream = $environment->addChild('data');
$datastream->addAttribute('id', $device['Name']);
$current_value = $datastream->addChild('current_value', $device['Value']);
$current_value->addAttribute('at', $iso8601_timestamp);
}
// Now either just return the newly constructed XML for an automatic Cosm feed
Header('Content-Type: text/xml');
print($cosm_xml->asXML());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment