<span><span>一些特殊字符</span><span>(</span><span>图标字符</span><span>)</span><span>在保存</span><span>mysql</span><span>时</span><span>,</span><span>不能插入数据库</span><span>可以先把字符</span><span>(</span><span>特殊字符和正常字符</span><span>)</span><span>用</span><span>base64_encode</span><span>转为</span><span>base64</span><span>编码</span><span>,</span><span>保存到</span><span>mysql</span><span>取出还原时</span><span>,</span><span>用</span><span>base64_decode</span><span>进行</span><span>base64</span><span>解码</span><span>,</span><span>再用</span><span>json_decode</span><span>还原为原字符</span></span>
参考网上资料整理
/** * 一些特殊字符(图标字符)在保存mysql时,不能插入数据库 * 可以先把字符(特殊字符和正常字符)用base64_encode转为base64编码,保存到mysql * 取出还原时,用base64_decode进行base64解码,再用json_decode还原为原字符 *//** * unicode解码 * @param $str * @return mixed|string */function unicode_decode($str){ if (!$str) return $str; $decode = json_decode($str); if ($decode) return $decode; $str = '["' . $str . '"]'; $decode = json_decode($str); if (count($decode) == 1) { return $decode[0]; } return $str;}//$re = unicode_decode('\u963f\u55b5\ud83d\udc31\ud83d\udca6');//echo($re);/** * unicode编码 * @param $str * @return string */function unicode_encode($str){ if (!$str) return $str; $decode = json_encode($str); if ($decode) return $decode; $str = '["' . $str . !本文来源gaodai#ma#com搞*!代#%^码网5搞gaodaima代码9;"]'; $decode = json_encode($str); if (count($decode) == 1) { return $decode[0]; } return $str;}//$re1 = unicode_encode('阿喵');//echo($re1);////////////////////////////////////////////////////////////////** * 对unicode字符进行base64编码,保存入库 */$conn = @mysql_connect("localhost","root","111111");if (!$conn){ die("连接数据库失败:" . mysql_error());}mysql_select_db("wx_sys", $conn);mysql_query("set character set 'gbk'"); //避免中文乱码字符转换mysql_query("set character set 'utf8'"); // PHP 文件为 utf-8 格式时使用//mysql_query("set names 'utf8'"); //PHP 文件为 utf-8 格式时使用//unicode码字符$name = '\u963f\u55b5\ud83d\udc31\ud83d\udca6';//正常中文//$name = '张三';//base64编码$re = base64_encode($name);$sql = "insert into test (uni) values ('" . $re . "')";if(!mysql_query($sql,$conn)){ echo "添加数据失败:".mysql_error();} else { echo "添加数据成功!";}//////////////////////** * 取出数据,base64解码,并还原字符 */$sql2 = "select * from test";$result = mysql_query($sql2)or die("无效查询: " . mysql_error());//循环从数据集取出数据while( $row = mysql_fetch_array($result) ){ $sr = base64_decode($row['uni']); $ab = unicode_decode($sr); echo "uni:".$ab."
";}以上就介绍了mysq,php写入unicode字符,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。