php5.4後htmlspecialchars輸出爲空的問題

從舊版升級到php5.4,恐怕最麻煩的就是htmlspecialchars這個問題了!當然,htmlentities也會受影響,不過,對於中文站來說一般用htmlspecialchars比較常見,htmlentities非常少用到。

可能老外認爲網頁普遍應該是utf-8編碼的,於是苦了那些用GB2312,GBK編碼的中文站......!

具體表現:

$str = "9enjoy.com的php版本是5.2.10";
echo htmlspecialchars($str);

gbk字符集下輸出爲空...utf-8下,輸出正常。

爲什麼呢,原因在於5.4.0對這個函數的變化:

5.4.0   The default value for the encoding parameter was changed to UTF-8.

原來是什麼呢?

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' [, bool $double_encode = true ]]] )

Defines encoding used in conversion. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.

原來是ISO-8859-1,5.4後默認變成utf-8!然後中文使用這個函數就輸出爲空白了。

國內一堆開源程序在5.4下都會有這樣的問題,DISCUZ官方也建議用戶不要升級到5.4。

解決方案:
1.苦逼的修改所有用到htmlspecialchars地方的程序

1.1 其第二個$flags參數,默認是ENT_COMPAT,因此改成
htmlspecialchars($str,ENT_COMPAT,'GB2312');
爲什麼不是GBK?因爲沒有GBK這個參數,如果強行使用GBK,則報錯給你看:
Warning: htmlspecialchars(): charset `gbk' not supported, assuming utf-8
爲了能使用GBK,則改成:
htmlspecialchars($str,ENT_COMPAT,'ISO-8859-1');

1.2.一樣是改程序,但可以省略一個參數。
可以在網頁頭部加
ini_set('default_charset','gbk');
然後改成
htmlspecialchars($str,ENT_COMPAT,'');
文檔中有寫:An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.
大概意思就是:傳入空字符串則使用default_charset的編碼

1.3.封裝一個函數吧...本來htmlspecialchars這個單詞一直不好記。
function htmlout($str) {
    return htmlspecialchars($str,ENT_COMPAT,'ISO-8859-1');
}
然後去批量替換。

2.直接修改源碼,重編譯!這也是目前我在線上做的方案。
修改ext/standard/html.c
大概在372行
/* Default is now UTF-8 */
if (charset_hint == NULL)
return cs_utf_8;
把cs_utf_8改成 cs_8859_1
/* Default is now UTF-8 */
if (charset_hint == NULL)
return cs_8859_1;
編譯後,原程序就不用做任何調整了。
安裝方法可參考:http://www.9enjoy.com/linux-upgrade-php54/

windows下怎麼辦?這個,自己想辦法編譯吧,難度比較大...
提供一個網址供參考:http://www.phpvim.net/web/php/build-php5-4-and-xdebug-on-win32.html

引用其一句話:準備好咖啡、可樂,做好準備,可能要折騰數小時…



原文網址:http://www.9enjoy.com/php54-htmlspecialchars/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章