Search code examples
phpxmlutc

Parsing Data XML to PHP and set timezone based on difference


I begain this quest to grab the date that this document was updated HERE but given my limited knowledge on this subject I hit a few road blocks.

  1. How to get to the actual time-stamp I desired.

a snip of the above XML file looks like:

     <data type="current observations">
         <time-layout time-coordinate="local">
              <start-valid-time period-name="current">2013-05-27T13:53:00-04:00</start-valid-time>
         </time-layout>
      </data>

I attempted the following but got an Invalid expression warning.

  $weather = simplexml_load_file('http://...');
  $time=$weather->xpath('//data[@type="current observations"]/"time-layout"/"start-valid-   time"');
  echo $time[0];

Hoping to get the following : 2013-05-27T13:53:00-04:00

Next i tried to set the default time zone based off this. I know that the -04:00 on the back of the time stamp is a indication of the difference from UTC. The following was a solution I hacked together and it works but Im not real fond of the method so any improvements or suggestions on how to do this better would be better.

  $time_UTC= substr($time,0,-6);
  $offset = substr($time,19,-3);
  $offsetfloat = (float)$offset;
  $timezoneName = timezone_name_from_abbr("", $offsetfloat*3600, false);
  date_default_timezone_set($timezoneName);

Solution

  • For your xpath-question - you were almost there, try:

    $time = $weather->xpath("//data[@type='current observations']/time-layout/start-valid-time");
    echo $time[0];
    

    with PHP >= 5.4, do this to get the first element only:

    $time = $weather->xpath("//data[@type='current observations']/time-layout/start-valid-time")[0];
    echo $time;   
    

    see it working: http://codepad.viper-7.com/PqPnzY

    Can't help with the timezone-issue, not my area.