在URL中使用特殊字符的PHP simplexml_load_file


PHP simplexml_load_file with special chars in URL

我正在尝试根据用户的IP检索本地天气预报。

我正在使用geoplogin.net获取用户位置,并将城市和国家名称输入到Google Weather API。

//Get user IP
$ip = $_SERVER['REMOTE_ADDR'];
$geolocation = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
$geo_city = $geolocation['geoplugin_city'];
$geo_country = $geolocation['geoplugin_countryName'];
$file = "http://www.google.com/ig/api?weather=".$geo_city.",".$geo_country;
$xml = simplexml_load_file($file);
//Echo content of retrieved XML for debugging purposes
echo "<pre>";
print_r($xml);
echo "</pre>";

它在大多数情况下都很好,但当我在自己的IP上尝试时,我会得到丹麦的瑟堡(不是100%准确,但足够接近),这给了我API天气的几乎是空的反应。

该案的主要嫌疑人是卑鄙的"ø"角色。

我想要的XML可以在这里看到:http://www.google.com/ig/api?weather=S%C3%B8borg,丹麦

我得到的XML可以在这里看到:http://www.google.com/ig/api?weather=S

当我在浏览器中键入这个URL时,它运行良好:

http://www.google.com/ig/api?weather=Søborg,Denmark

当我使用这个版本时,它也能工作(在浏览器中):

http://www.google.com/ig/api?weather=S%C3%B8borg,Denmark

但这个版本返回了对博格的预测,Syddanmark:

http://www.google.com/ig/api?weather=S%26oslash%3Bborg,Denmark

当提供给simplexml_load_file()时,以上所有操作都不会返回所需的结果。

如上所述,我怀疑这是一个字符集问题,但我不知道该怎么办

解决问题的正确方法是什么?

我知道我可以使用纬度和经度作为Google Weather API的参数,但这只是规避问题,而不是解决问题。

如果你对S%26oslash%3Bborg进行URL解码,你会发现这个字符串对应于S&oslash;borg,在我们解码HTML实体后,它给了我们Søborg,比如:

$city = 'S%26oslash%3Bborg,Denmark';
echo $city = rawurldecode($city);
//prints S&oslash;borg,Denmark
echo $city = html_entity_decode($city, 0, 'UTF-8');
//prints Søborg,Denmark
echo $city = rawurlencode($city);
//prints S%C3%B8borg%2CDenmark

然后:

$xml = file_get_contents('http://www.google.com/ig/api?weather='.$city);
$xml = mb_convert_encoding($xml, 'UTF-8');
$xml = simplexml_load_string($xml);
echo $xml->weather->forecast_information->city['data'];

预期输出:

Søborg, Capital Region of Denmark

这听起来确实像是一个字符集问题。在将结果传递到simplexml_load_file()之前,您是否尝试过将URL转换为其他编码,例如使用iconv?

试试这个:

$file = "http://www.google.com/ig/api?weather=" . $geo_city . "," . $geo_country;
$data = file_get_contents($file);
$data = mb_convert_encoding($data, "UTF-8", "ISO-8859-2");
$xml = simplexml_load_string($data);
echo "<pre>"; print_r($xml); echo "</pre>";

它取自这个可能类似的线索:https://stackoverflow.com/a/5136549/949476