0

I am trying to read XML elements that have a "-" in the name. The feed can be found at http://forecast.weather.gov/MapClick.php?lat=42.19774&lon=-121.81797&FcstType=dwml In my last question I was just trying to read any of them. reading a XML feed with '-' in some of the element names Now I am trying to read a particular one(other than the first) and I am getting stumped again.

This will get me the first time-layout and the first start-valid-time.

$time = $xml->data->{'time-layout'}->{'start-valid-time'};

I am after the second time-layout and I want to read through the attributes of the start-valid-time elements.

Below is a way that I have found that works. What I have done below cannot be the correct way to go about this. How should a person normally go about doing this?

Thanks.

     $time = $xml->data->{'time-layout'};
     $time2= $time[1]->{'start-valid-time'};
     $count= 14;
      for ($i = 0; $i <=$count ; $i++)
      {
         echo $time2[$i]->attributes();
         print "<br>\n";
      }
Community
  • 1
  • 1
Brandan
  • 307
  • 1
  • 4
  • 12

2 Answers2

0

For this type of queries XPath is invented

Ward Bekker
  • 6,316
  • 9
  • 38
  • 61
  • [How to write a good answer](http://meta.stackexchange.com/questions/7656/how-do-i-write-a-good-answer-to-a-question) – Gordon May 10 '11 at 07:57
0

What you do is correct. You could shorten to

$dwml = simplexml_load_file('http://…');
foreach ($dwml->data->{'time-layout'}[1]->{'start-valid-time'} as $time) {
    echo $time;
}

or use XPath

$dwml = simplexml_load_file('http://…');
foreach ($dwml->xpath('/dwml/data/time-layout[2]/start-valid-time') as $time) {
    echo $time;
}
Gordon
  • 312,688
  • 75
  • 539
  • 559