如图所示,我的主页包含全球三个城市的天气
在主页中,我声明了 3 个变量,用于存储每个城市的 RSS URL
$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';
我从上面显示的三个 URL 中提取相同的标签,并使用除了传递给它的变量之外的 3 个相同的函数。
下面显示了传递给函数的变量。显然,在返回 $weather 之前使用了其他函数。
function new_york_current_weather($newYorkWeatherSource) {
// Get XML data from source
if (isset($newYorkWeatherSource)) {
$feed = file_get_contents($newYorkWeatherSource);
} else {
echo 'Feed not found. Check URL';
}
checkWeatherFeedExists($feed);
$xml = new SimpleXmlElement($feed);
$weather = get_dateTime($xml);
$weather = get_temperature_and_convert($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
正如我所提到的,我当前重复此函数 3 次,只是替换了上面示例中传递的 $newYorkWeatherSource 变量。有什么想法可以重复使用此功能 3 次,但传递不同的 URL 以保持我的主页显示来自 3 个城市的天气?当然,如果每个城市都在单独的页面上表示,则很容易重用该功能,但目的是将它们放在一起以进行比较。
有任何想法吗?
提前致谢。