使用simplexml_load_string显示数组值

时间:2013-04-23 12:26:39

标签: php xml api

我需要从xml输出中获取一些数据:

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

    )

我正在使用

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

输出温度和天气代码,工作正常,输出:

Current temperature 18 and code 116

现在我如何从Weather Array [0]中获取TempMaxC和TempMinC 以及数组[1]

由于

1 个答案:

答案 0 :(得分: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>";
}