PHP中的URL解码

36
我正在尝试使用PHP的urldecode函数解码这个URL字符串。
urldecode("Ant%C3%B4nio+Carlos+Jobim");

这段代码应该输出...

'Antônio Carlos Jobim'

...但实际输出的是这个

'Antônio Carlos Jobim'

我已经在基于JS的在线解码器中成功地测试了该字符串,但似乎无法在服务器端执行此操作。有什么想法吗?


1
你正在使用哪种方法输出它? - Alistair Evans
6个回答

70

你的字符串 是 UTF-8 编码。这样会起作用:

echo utf8_decode(urldecode("Ant%C3%B4nio+Carlos+Jobim"));

输出结果: "Antônio Carlos Jobim"。


6
只有在页面声明了“ISO-8859-1”编码时才适用。 - Kornel

14

实际上,您可以得到所需的输出,但它没有被解释为UTF-8。 如果这是在HTTP应用程序中,则应发送一个头部或元标记(或两者兼而有之),告诉客户端使用UTF-8。

编辑:例如:

// replace text/html with the content type you're using
header('Content-Type: text/html; charset=UTF-8');

3

当我执行时

<?php
echo urldecode("Ant%C3%B4nio+Carlos+Jobim");
?>

我的浏览器中正确显示如下:

Antônio Carlos Jobim

我已经使用XAMPP进行了测试。


3
另一个选项是:
<?php
$smthing = 'http%3A%2F%2Fmysite.com';
$smthing = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($smthing)); 
$smthing = html_entity_decode($smthing,null,'UTF-8');
echo $smthing;
?>

输出结果为:http://mysite.com

这个可以工作。只有urldecode()无法解码带有查询参数的整个URL。 问题是你的解决方案思考时间太长了 :/ - temo

1

在将其回显到页面之前,您是否也使用了htmlenteties?当我刚测试您的代码时,只有urldecode("Ant%C3%B4nio+Carlos+Jobim");这一部分就可以正常工作了,但是当我通过htmlentites运行它时,我得到了与您相同的输出。

这似乎是UTF-8字符及PHP处理htmlentities函数的问题。


1
如果您将正确的编码作为$charset参数指定,则它将正常工作。无论如何,如果您只想保护免受XSS攻击,那么您应该使用htmlspecialchars而不是htmlentities - Ignas R

-2

首先你需要在"urldecoder()"函数中解码,然后使用utf解码器函数"utf_decoder()"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接