XML到PHP的变量

时间:2013-06-19 11:15:24

标签: php xml variables xml-parsing

我的xml-php脚本有问题。 XML doc:http://www.yr.no/place/Sweden/Stockholm/Stockholm/forecast.xml

$xmlstr = "http://www.yr.no/place/Sweden/Stockholm/Stockholm/forecast.xml";

//$vader = new SimpleXMLElement($xmlstr);
$vader = simplexml_load_file($xmlstr);

foreach ($vader->forecast->tabular->time->temperature as $temp) {
   echo $temp->temperature, ' ', $temp->windSpeed, PHP_EOL;
}

我想要一个名为$temp

的变量中的温度

2 个答案:

答案 0 :(得分:0)

如果要获得输出

echo $ temp-> temperature,'',$ temp-> windSpeed,PHP_EOL;

然后您可以获得以下的温度值

PHP代码:

    $temp_array = array();
    $tempt_str = ''
    $i = 0;
    foreach ($vader->forecast->tabular->time->temperature as $temp) {
       $tempt_str .= 'temperature : '.$temp->temperature.''.'windSpeed : '.$temp->windSpeed.'<br/>';
       $temp_array[$i]['temperature'] = $temp->temperature;
       $temp_array[$i]['windSpeed'] = $temp->windSpeed;
    }

答案 1 :(得分:0)

有多个<time>,所以你可以循环它们。此外,temperaturewindSpeed属于属性。

foreach ($vader->forecast->tabular->time as $time) {
   echo $time->temperature->attributes()->value, ' ', $time->windSpeed->attributes()->mps, PHP_EOL;

   // or store temperature in a variable?
   // $temp = $time->temperature;
   // echo $temp->attributes()->value; // 14
   // echo $temp->attributes()->unit; // celcius
}

或仅访问第一个<time>

echo $vader->forecast->tabular->time[0]->temperature->attributes()->value;
echo $vader->forecast->tabular->time[0]->windSpeed->attributes()->mps;