SimpleXML在数组中存储属性

时间:2016-08-19 11:49:28

标签: php html xml simplexml openweathermap

我的代码有点工作,但我没有得到我想要的输出,我只是想要输出“Gentle Breeze”,而是我得到“SimpleXMLElement Object([0] => Gentle Breeze)”

这是我的代码:

<head>
    <title>Open Weather API</title>
</head>

<body>
    <?php
    $url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=xml&units=metric&cnt=16&appid=Key";
    $xml = simplexml_load_file($url);

    foreach($xml->forecast->time as $times)
    {
        $windspeed[] = $times->windSpeed["name"];
    }

    print_r($windspeed[0])
?>
</body>

我尝试过使用echo而不是print_r,但输出的只是“Array”

以下是我从API中提取的XML示例:

<time day="2016-08-19">
  <symbol number="500" name="light rain" var="10d"/>
  <precipitation value="2.97" type="rain"/>
  <windDirection deg="188" code="S" name="South"/>
  <windSpeed mps="5.28" name="Gentle Breeze"/>
  <temperature day="22.58" min="17.06" max="22.58" night="18.39" eve="18.61" morn="17.06"/>
  <pressure unit="hPa" value="1012.32"/>
  <humidity value="72" unit="%"/>
  <clouds value="overcast clouds" all="92" unit="%"/>
</time>

我需要将它存储在一个数组中,以便我稍后可以在我的代码中调用它,我只是输出结果作为测试来查看存储在数组中的内容,我只是希望它存储“Gentle Breeze” “not”SimpleXMLElement Object([0] =&gt; Gentle Breeze)“

2 个答案:

答案 0 :(得分:2)

简单的转换为字符串应该达到你想要的效果:

foreach($xml->forecast->time as $times)
{
    $windspeed[] = (string) $times->windSpeed["name"];
}

答案 1 :(得分:-1)

尝试这样做:

$windspeed[] = $times->windSpeed->name;

var_dump ($times->windSpeed->name);