PHP 写入Mysql数据库,标记语言出现特殊符号!

December 23rd, 2011 by admin Leave a reply »

数据存入数据库时,会自动对<,单引号等特殊符号转码,读取时再还原,主要是为了安全考虑,譬如&会变成& 等等。

解决方法:
可以尝试使用函数
html_entity_decode($str)
将内容还原为HTML,这样就可以了。
详情参考:

http://www.w3school.com.cn/php/func_string_html_entity_decode.asp

当我们需要根据html数据去查询数据库的时候,就需要反过来,因为在数据库中&‘<等符号都是编码过的,就需要用到下面的自定义函数,将html存在的特殊符号编码以便和数据库一致。

附函数html_entity_encode($str)

function html_entity_encode($str) {
preg_match_all("/[\x{4e00}-\x{9fa5}]|./iu",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(ord($v[0]) < 128) {
$ar[$k] = htmlentities($v);
} else {
$v = iconv(“UTF-8″,”UCS-2″,$v);
$ar[$k] = “&#”.((ord($v[0]) << 8) + ord($v[1])).’;';
}
}
return join(“”,$ar);
}

Advertisement

Leave a Reply

What is 9 + 3 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)