php呼叫微信用戶資訊介面暱稱裡面的emoji表情怎麼儲存到mysql?
天蓬老师
天蓬老师 2017-05-16 13:06:54
0
3
887

如題:目前確定是將獲取到的字串轉為unicode編碼儲存到表中,表的編碼是utf-8;現在遇到的問題是:如果使用json_encode()函數多次轉義後儲存到資料庫中的字串多了幾層的雙引號,如果只轉義一次存儲到資料庫中雖然沒有了引號,但是符號不見了,如下圖,後面附關鍵代碼,新手諮詢存儲的正確方式;

看到答案都是需要將資料庫字元集改為:utf8mb4,想知道不用這個字元集用utf-8不可以嗎?新手只知道在my.ini修改全域的字元集,不知道怎麼針對這個欄位來修改啊。

最新更新:經過測試雖然utf8mb4能夠將資料儲存到資料庫中,但還是有問題的:如果微信暱稱前後面都有表情,中間有文字的時候,資料庫中只能將前面的表情保存,後面的表情變成了空格,經過幾番周折還是使用了utf8來保存下圖藍色條選中的那樣字符串來保存,在前端對字符串進行去"處理,保證用戶的暱稱不被破壞,如果各位有更好的辦法歡迎留言。

關鍵代碼:

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;
  }
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(3)
仅有的幸福
  1. mysql欄位設定為utf8mb4-utf8mb4-general_ci

  2. php

<?php
json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
phpcn_u1582

表支持utf8mb4的話, 換成utf8mb4, 沒有用就utf32吧, utf8只支持少量的emoji表情

查詢前, 先執行 $conn->query("set names utf8") 確保資料傳輸過程不亂碼

emoji 也是字符, 沒必要轉json

我想大声告诉你

utf-8使用3個位元組進行存儲,而emoji字元有4個字節,因此將utf-8轉換為utf8mb4即可解決

另外注意:mysql的版本必須為v5.5.3或更高

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!