2009-11-18 132 views
24

我試圖使用PHP的urldecode函數這個URL字符串解碼:URL解碼在PHP

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

據說這是爲了輸出...

'Antônio Carlos Jobim' 

...而是被ouptutting這

'Antônio Carlos Jobim' 

我測試過的非常成功JS-based online decoder字符串,但似乎無法做到這一點operati在服務器端。有任何想法嗎?

+1

什麼方法您使用的輸出呢? – Kazar 2009-11-18 15:47:14

回答

47

您的字符串是也是 UTF-8編碼。這將工作:

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

產量:「AntônioCarlos Jobim」。

+4

只有頁面聲明爲「ISO-8859-1」編碼。 – Kornel 2009-11-26 12:58:30

12

實際上,您會得到所需的輸出,但它不會被解釋爲UTF-8。如果這是在HTTP應用程序上,您應該發送一個頭部或元標記(或兩者),這會告訴客戶端使用UTF-8。

編輯:例如:

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

你也呼應它的頁面之前使用htmlenteties?當我剛剛測試你的代碼時,它只能運行urldecode("Ant%C3%B4nio+Carlos+Jobim");部分,但是當我通過htmlentities運行時,我得到的輸出和你一樣。

這似乎是UTF-8字符的問題,以及PHP如何處理htmlentities函數。

+1

如果您指定正確的編碼爲'$ charset'參數,它將正常工作。無論如何,如果你想做的只是防止XSS,你應該使用'htmlspecialchars',而不是'htmlentities'。 – 2009-11-18 15:48:55

1

當我做

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

其正確顯示在我的瀏覽器,如

安東尼奧·卡洛斯·裘賓

我與XAMPP

0

測試的另一種選擇是:

<?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