2016-08-19 30 views
0

我的代碼是有點工作,但我沒有得到我想要的輸出,我從字面上只是想輸出「溫柔的微風」,而是我得到「SimpleXMLElement對象([0] = >微風)」SimpleXML在一個數組中存儲屬性

這裏是我的代碼:

<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> 

我一直在使用的回聲,而不是試圖print_r的但被輸出的都是 「陣列」

這裏是我從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> 

我需要將其存儲在一個數組,所以我可以在我的代碼以後調用它,我只是在輸出結果作爲一個測試,看看什麼是存儲在陣列中,我只是希望它來存儲「微風」不是「SimpleXMLElement對象([0] =>微風)」

+0

看起來像一個多維數組,嘗試'回聲$風速[0] [0]' –

+0

我已經試過了,它沒有似乎工作 –

回答

2

一個簡單的強制轉換爲字符串應該達到你想要的東西:

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

謝謝 –

-1

儘量不要做這樣的:

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

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

不存儲在一個數組? –

+0

我更新了我的答案,但只是給你一個例子,看看該屬性是否解析爲鍵入字符串 – GreensterRox

+1

我需要使用$ windspeed [] = $ times-> windSpeed [「name」];如果我只輸入echo $ xml-> forecast-> time-> windSpeed [「name」];我得到了輸出「溫和的微風」,所以我不明白爲什麼數組存儲的東西不同 –

相關問題