如何从ipaddress中检索天气信息

时间:2012-12-26 05:49:43

标签: xml yii weather-api

我在Yii + extjs工作。我正在创建天气模块。我想从用户的ipaddress中检索天气信息。我从网站=“http://www.geoplugin.com/examples”获得了参考代码。 按照那里提到的,我创建了getweather函数as =

                  public function actionGetWeather()
        {
            $user_ip = $_SERVER['REMOTE_ADDR'];
            //The Data Science Toolkit URL
            $url = 'http://www.datasciencetoolkit.org/ip2coordinates/';
            //Find the user's location from their IP.
            //*** You need the get_data function from the sample code
            $raw_geocode = json_decode( get_data( $url . $user_ip) );
            //Check if the user is in the US
            if ('US' === $raw_geocode->$user_ip->country_code) {
                //If yes, store their zip code in a variable, and print it
                $zip_code = $raw_geocode->$user_ip->postal_code;
                printf('<p>Your zip code is: %s</p>', $raw_geocode->$user_ip->postal_code);
            } else {
                //If the user isn't in the US, set a sip code that will work.
                $zip_code = '97211';
                //and print an error
                printf('<p>Sorry, this app does not work in %s.</p>', $raw_geocode->$user_ip->country_name);
            }

            //Print the raw data for debugging.
            printf('<pre>%s</pre>', print_r($raw_geocode, true));
        }

我在我的项目中也包含了ParseXml类。 但上面的代码给出了错误,因为致命错误:在“$ raw_geocode = json_decode(get_data($ url。$ user_ip))”中调用未定义函数get_data();“的天气功能。那么我需要改变什么呢?请帮帮我

1 个答案:

答案 0 :(得分:0)

如果您使用curl,请将get_data()的定义包括为..

function get_data($url)
{
     $ch = curl_init();
     $timeout = 5;
     curl_setopt($ch,CURLOPT_URL,$url);
     curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
     curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
     $data = curl_exec($ch);
     curl_close($ch);
     return $data;
}

或者,只需替换

     $raw_geocode = json_decode( get_data( $url . $user_ip) );

...与

     $raw_geocode = json_decode(file_get_contents( $url . $user_ip) );