如果无效的网址,PHP File_get_contents会取消

时间:2013-06-10 08:57:29

标签: php url escaping character

我刚刚将bing地图嵌入到我的网站中,并且查询字符串以获得纬度和经度对每个用户都是可变的。不幸的是,在我的免费国家和城市的数据库中,我有一些糟糕的符号,例如在这个位置Bouaké, Côte d’Ivoire中,file_get_contents()函数无法读取这些符号,因为它们变成了Bouaké,%20Côte%20d’Ivoire 。谁能告诉我如何逃避这些角色?实际上我也很乐意将它们删除或者用他们的英语联想代替é -> e。提前谢谢!

2 个答案:

答案 0 :(得分:2)

Bouaké,%20Côte%20d’Ivoire字符串看起来已经被转义但是对于html。您必须使用html_entity_decode()将其转换回来,然后为了网址,rawurlencode()将您的字符串转换为低谷。

如果您可以在没有html实体的情况下访问您的输入,只需在这些字符串上使用rawurlencode(),然后再将其添加到您的请求网址。

更新

从你的评论看来,简单地按原样发送名称是行不通的。您可以尝试用非重音字母替换已加入的字母。为此,您需要在php环境和iconv中安装适当的语言环境(假设您的输入是在utf8中):

$str = 'Bouaké,%20Côte%20d’Ivoire';
$old_locale = setlocale(LC_ALL, 'en_US.UTF8'); // setting the locale to an english one, saving the old
$ascii = iconv(
    'UTF-8',
    'ASCII//TRANSLIT//IGNORE', html_entity_decode($str, ENT_QUOTES, 'utf-8')
); // convert input to ascii transliterate from the locale data and ignore anything that cant be transliterated.
setlocale(LC_ALL, $old_locale); // restore the old locale
print rawurlencode($ascii); // => shoud print Bouake%2C%2520Cote%2520d%27Ivoire

这应该将您的字符串转换为可以编码的asccent free ascii(例如,对于' -s)。

答案 1 :(得分:0)

使用iconv()进行请求的字符编码。

$data = file_get_contents('http://www.example.com/');
iconv("UTF-8", "ISO-8859-1", $data);