以下是一个简单的多城市PHP代码示例,用于获取不同城市的天气信息:
<?php
// 定义城市列表
$cityList = [
'北京' => '101010100',
'上海' => '101020100',
'广州' => '101280101',
'深圳' => '101280601',
// 添加更多城市...
];
// 获取城市天气信息的函数
function getWeather($cityCode) {
// 构建API URL
$url = "http://www.weather.com.cn/data/cityinfo/{$cityCode}.html";
// 发起HTTP请求
$response = file_get_contents($url);
// 解析JSON响应
$data = json_decode($response, true);
// 提取天气信息
$weather = $data['weatherinfo']['weather'];
$temp = $data['weatherinfo']['temp'];
// 返回天气信息
return "天气:{$weather},温度:{$temp}℃";
}
// 遍历城市列表,获取天气信息
foreach ($cityList as $city => $cityCode) {
$weather = getWeather($cityCode);
echo "{$city}的天气信息:{$weather}\n";
}
请注意,此示例仅用于演示目的,实际使用时可能需要根据具体需求进行修改和优化。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站