2013-04-23 51 views
0

我需要從一個XML輸出一些數據:使用顯示數組值與simplexml_load_string

printf("<p>Current temperature %s and code %s</p>", 
    $xml->current_condition->temp_C, $xml->current_condition->weatherCode); 

以輸出溫度和天氣代碼,

[current_condition] => SimpleXMLElement Object 
    (
     [observation_time] => 12:22 PM 
     [temp_C] => 18 
     [temp_F] => 64 
     [weatherCode] => 116 
     [weatherIconUrl] => SimpleXMLElement Object 
      (
      ) 

     [weatherDesc] => SimpleXMLElement Object 
      (
      ) 

     [windspeedMiles] => 4 
     [windspeedKmph] => 7 
     [winddirDegree] => 180 
     [winddir16Point] => S 
     [precipMM] => 0.1 
     [humidity] => 52 
     [visibility] => 10 
     [pressure] => 1023 
     [cloudcover] => 50 
    ) 

[weather] => Array 
    (
     [0] => SimpleXMLElement Object 
      (
       [date] => 2013-04-23 
       [tempMaxC] => 20 
       [tempMaxF] => 69 
       [tempMinC] => 7 
       [tempMinF] => 44 
       [windspeedMiles] => 5 
       [windspeedKmph] => 8 
       [winddirection] => SSW 
       [winddir16Point] => SSW 
       [winddirDegree] => 210 
       [weatherCode] => 113 
       [weatherIconUrl] => SimpleXMLElement Object 
        (
        ) 

       [weatherDesc] => SimpleXMLElement Object 
        (
        ) 

       [precipMM] => 0.7 
      ) 

     [1] => SimpleXMLElement Object 
      (
       [date] => 2013-04-24 
       [tempMaxC] => 25 
       [tempMaxF] => 76 
       [tempMinC] => 8 
       [tempMinF] => 46 
       [windspeedMiles] => 3 
       [windspeedKmph] => 5 
       [winddirection] => NNE 
       [winddir16Point] => NNE 
       [winddirDegree] => 24 
       [weatherCode] => 113 
       [weatherIconUrl] => SimpleXMLElement Object 
        (
        ) 

       [weatherDesc] => SimpleXMLElement Object 
        (
        ) 

       [precipMM] => 0.3 
      ) 

    ) 

Im和工作正常,則outputing:

Current temperature 18 and code 116 

現在,我怎麼TempMaxC和TempMinC從天氣數組[0] ,也從陣列[1]

感謝

+0

你知道什麼是一個循環?你有沒有聽說過http://php.net/foreach?我只是問,因爲單從你的問題來看,你不清楚你在哪裏碰到路障。 – hakre 2013-04-23 17:05:40

回答

0

您可以使用foreach

foreach($xml->weather as $weatherObj) { 
    echo "<h2>Weather on {$weatherObj->date}</h2>"; 
    echo "<ul>"; 
    echo "<li>Max temp: {$weatherObj->tempMaxC}</li>"; 
    echo "<li>Min temp: {$weatherObj->tempMinC}</li>"; 
    echo "</ul>"; 
}