Heim > Fragen und Antworten > Hauptteil
如题:目前确定是将获取到的字符串转为unicode编码存储到表中,表的编码是utf-8;现在遇到的问题是:如果使用json_encode()函数多次转义后存储到数据库中的字符串多了好几层的双引号,如果只转义一次存储到数据库中虽然没有了引号,但是 符号不见了,如下图,后面附关键代码,新手咨询存储的正确方式;
关键代码:
function weixininfo($code){
$userinfo = getJson($get_user_info_url);
$wxif = new wxinfo($userinfo["openid"],$userinfo["nickname"],$userinfo["sex"],$userinfo["headimgurl"]);
class Emp {};
$obj = new Emp();
$obj->result = 0;
$obj->info = $wxif;
return $obj;
}
$code = $_GET['code'];
$data = weixininfo($code);
$info = $data->info;
$openid = $info->openid;
$nickname = $info->nickname;
$name = json_encode($nickname);
$sex = $info->sex;
$headurl = $info->headurl;
$sqls = "INSERT INTO mytest(openid,nickname,sex,headurl) VALUES ('$openid',$name,'$sex','$headurl')";
if($conn->query($sqls) === true){
session_start();
$_SESSION["openid"]=$openid;
$conn->close();
// $uri ="./index.php";
// header( "Location: $uri" );
}else{
echo "失败:".$sqls."<br>".$conn->error;
};
function getJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
class wxinfo {
public $openid;
public $nickname;
public $sex;
public $headurl;
public function __construct($openid,$nickname,$sex,$headurl){
$this->openid = $openid;
$this->nickname = $nickname;
$this->sex = $sex;
$this->headurl = $headurl;
}
}
仅有的幸福2017-05-16 13:08:54
mysql字段设置为utf8mb4
-utf8mb4-general_ci
php
<?php
json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
phpcn_u15822017-05-16 13:08:54
表支持utf8mb4的话, 换成utf8mb4, 没有用就utf32吧, utf8只支持少量的emoji表情
查询前, 先执行 $conn->query("set names utf8") 保证数据传输过程不乱码
emoji 也是字符, 没必要转json
我想大声告诉你2017-05-16 13:08:54
utf-8使用3个字节进行存储,而emoji字符有4个字节,因此将utf-8转换为utf8mb4即可解决
另外注意:mysql的版本必须为v5.5.3或更高