php5.4后htmlspecialchars輸出為空解決方法

2016年3月3日01:30:56 發(fā)表評論 3,655 ℃

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

可能老外認為網(wǎng)頁普遍應(yīng)該是utf-8編碼的,于是苦了那些用GB2312,GBK編碼的中文站......!

具體表現(xiàn):

$str = "9enjoy.com的php版本是5.2.10";

echo htmlspecialchars($str);

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

為什么呢,原因在于5.4.0對這個函數(shù)的變化:

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!然后中文使用這個函數(shù)就輸出為空白了。

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

解決方案:

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

1.1 其第二個$flags參數(shù),默認是ENT_COMPAT,因此改成

htmlspecialchars($str,ENT_COMPAT,'GB2312');

為什么不是GBK?因為沒有GBK這個參數(shù),如果強行使用GBK,則報錯給你看:

Warning: htmlspecialchars(): charset `gbk' not supported, assuming utf-8

為了能使用GBK,則改成:

htmlspecialchars($str,ENT_COMPAT,'ISO-8859-1');

1.2.一樣是改程序,但可以省略一個參數(shù)。

可以在網(wǎng)頁頭部加

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.封裝一個函數(shù)吧...本來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;

編譯后,原程序就不用做任何調(diào)整了。

【騰訊云】云服務(wù)器、云數(shù)據(jù)庫、COS、CDN、短信等云產(chǎn)品特惠熱賣中

發(fā)表評論

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: