Google Weather API - parsing and modifying data

僤鯓⒐⒋嵵緔 提交于 2019-12-02 00:01:59

Encoding problem:

For some reason Google returns the XML content without proper encoding declaration. One would expect something like:

<?xml version='1.0' encoding='ISO-8859-2'?>

But they skip the encoding attribute in the header. This makes the simplexml_load_file function assume the default encoding of UTF-8. I would consider this a bug in their API implementation, since the XML spec defines UTF-8 as the fallback default encoding.

To compesate for this, try something like:

<?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);
...

Which seems to work. The ISO-8859-2 value was a pure guess.

Fahrenheit/Celsius:

I don't see an easy way to request the temperature data to be provided in Celsius instead of Fahrenheit in this API (I couldn't find the official doc, am I blind?). However conversion from F to C shouldn't be hard at all.

Try this formula:

(°F  -  32)  x  5/9 = °C

which you can find in thousand of places. I took it from http://www.manuelsweb.com/temp.htm

The google xml does return the temperature in Celsius as well look for a temp_c tag inside current_conditons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!