这个问题不再是最新的——谷歌在 2012 年关闭了非官方的天气 API
我想把一些天气预报放到朋友的网页上。当我为
http://www.google.com/ig/api?weather=koprivnica,croatia&hl=hr
浏览器使用以下代码返回我想解析到 PHP 的正确内容:
<?php
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=koprivnica,croatia&hl=hr');
$information = $xml->xpath("/xml_api_reply/weather/forecast_information");
$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
$forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>VREMENSKA PROGNOZA</title>
</head>
<body>
<h1><?= print $information[0]->city['data']; ?></h1>
<h2>Danas</h2>
<div class="weather">
<img src="<?= 'http://www.google.com' . $current[0]->icon['data']?>" alt="weather"?>
<span class="condition">
<?= $current[0]->temp_f['data'] ?>° F,
<?= $current[0]->condition['data'] ?>
</span>
</div>
<h2>Prognoza</h2>
<?php foreach ($forecast_list as $forecast) : ?>
<div class="weather">
<img src="<?= 'http://www.google.com' . $forecast->icon['data']?>" alt="weather"?>
<div><?= $forecast->day_of_week['data']; ?></div>
<span class="condition">
<?= $forecast->low['data'] ?>° F - <?= $forecast->high['data'] ?>° F,
<?= $forecast->condition['data'] ?>
</span>
</div>
<?php endforeach ?>
</body>
</html>
但是上面的代码不起作用,因为我使用了“hr”而不是“en”(hr = 克罗地亚语):
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=koprivnica,croatia&hl=en')
是工作语法,但返回的数据是英文的,温度是华氏温度。
我想这是错误的 UTF-8 编码属性的问题。
我不知道如何获取确切的克罗地亚语文本并将华氏度转换为摄氏度。
后来我找到了F-to-C 解决方案的链接,并更改了第 19 行:
<?= $current[0]->temp_f['data'] ?>° F,
至
<?= $current[0]->temp_c['data'] ?>° C,
(我在当前版本中没有使用它,因为 API 似乎可以处理摄氏度。)
要在将语言设置为“en”的同时保持 C 中的度数,您可以使用
en-gb
.