这个问题不再是最新的-Google在2012年关闭了非官方的天气API
我想在朋友的网页上放一些天气预报.
当我为
http://www.google.com/ig/api?weather=koprivnica,croatia&hl=hr
<?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')
是有效的语法,但返回的数据为英文,温度为华氏温度.
我不知道如何获取确切的克罗地亚语文本并将F转换为摄氏度.
>之后,我找到了指向F-to-C solution的链接,并更改了第19行:
<?= $current [0]-> temp_f [‘data’]?& deg; F,
至
<?= $current [0]-> temp_c [‘data’]& deg; C,
(在当前版本中,我不使用它,因为它似乎可以处理摄氏温度.)
>若要在将语言设置为“ en”的同时将度数保持在C中,可以使用en-gb.
解决方法:
编码问题:
由于某种原因,Google会返回XML内容,而没有正确的编码声明.人们会期望像:
<?xml version='1.0' encoding='ISO-8859-2'?>
但是它们会跳过标头中的encoding属性.这使simplexml_load_file函数采用UTF-8的默认编码.从XML spec defines UTF-8 as the fallback default encoding开始,我认为这是他们API实现中的错误.
要对此进行补偿,请尝试以下操作:
<?PHP
$URL = "http://www.google.com/ig/api?weather=koprivnica,croatia&hl=hr";
$dataInISO = file_get_contents($URL);
$dataInUTF = mb_convert_encoding($dataInISO, "UTF-8", "ISO-8859-2");
$xml = simplexml_load_string($dataInUTF);
...
这似乎可行. ISO-8859-2值是一个纯粹的猜测.
华氏/摄氏:
我看不到一种简单的方法来请求在此API中以摄氏度代替华氏温度提供温度数据(我找不到官方文档,我是盲人吗?).但是,从F到C的转换并不难.
试试这个公式:
(°F - 32) x 5/9 = °C
您可以在数千个地方找到它.我从http://www.manuelsweb.com/temp.htm拿走了
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。