Use php to write a weather forecast Module
Weather data is collected through the Chinese meteorological website. Originally, the China weather website also provided APIs for data. The following is the API address. The returned data is in json format.
1. http://www.weather.com.cn/data/sk/101010100.html
2. http://www.weather.com.cn/data/cityinfo/101010100.html
3. http://m.weather.com.cn/data/101010100.html
The number "101010100" in the URL is the city code. So you can first list the city code of each city, then the php program receives the city code, and then assemble the URL to display the real-time weather of the city through the URL.
Index. php
Copy codeThe Code is as follows:
<? Php
Header ("Content-Type: text/html; charset = UTF-8 ");
?>
<Html>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Head>
<Title> weather forecast </title>
<Script type = "text/javascript" src = "ajax. js"> </script>
<Script type = "text/javascript">
Function $ (id ){
Return document. getElementById (id );
}
Function getCityId (){
Var http_request = createAjax ();
Var url = "weatherforecast. php"
Var data = "cityid =" + $ ("cityId"). value;
Http_request.onreadystatechange = getWetherInfo;
Http_request.open ("post", url, true );
Http_request.setRequestHeader ("Content-type", "application/x-www-form-urlencoded ");
Http_request.send (data );
Function getWetherInfo (){
If (http_request.readyState = 4 & http_request.status = 200 ){
Var info = http_request.responseText;
$ ("Weatherinfo"). innerHTML = info;
}
}
}
</Script>
</Head>
<Body>
<Select name = "cityId" onchange = "getCityId ();" id = "cityId">
<Option> -- select a city. </option>
<Option value = "101010100"> Beijing </option>
<Option value = "101020100"> Shanghai </option>
<Option value = "101030100"> Tianjin </option>
<Option value = "101040100"> Chongqing </option>
<Option value = "101280101"> Guangzhou </option>
</Select>
<Span id = "weatherinfo"> </span>
</Body>
</Html>
Weatherforecast. php
Copy codeThe Code is as follows:
<? Php
Header ("Content-Type: text/html; charset = UTF-8 ");
Header ("Cache-Control: no-cache ");
If (isset ($ _ POST ['cityid']) {
$ Cityid = $ _ POST ['cityid'];
$ Url = "http://www.weather.com.cn/data/sk/". $ cityid. ". html ";
} Else {
$ Url = "http://www.weather.com.cn/data/sk/101010100.html ";
}
$ WeatherInfo_json = file_get_contents ($ url );
$ WeatherInfo = json_decode ($ weatherInfo_json, true );
$ CityName = $ weatherInfo ['weatherinfo'] ['city'];
$ CityTemp = $ weatherInfo ['weatherinfo'] ['temp '];
$ CityWd = $ weatherInfo ['weatherinfo'] ['wd '];
$ CityWs = $ weatherInfo ['weatherinfo'] ['ws'];
$ CityTime = $ weatherInfo ['atherinfo'] ['time'];
$ CitySD = $ weatherInfo ['weatherinfo'] ['sd'];
Echo $ weatherinfo = "city name: $ cityName, temperature: $ cityTemp, wind direction: $ cityWd ";
?>