php json數(shù)據(jù)中文亂碼問題的解決辦法:1、打開相應(yīng)的php文件;2、在“json_encode()”方法中添加一個參數(shù)“JSON_UNESCAPED_UNICODE”即可正常輸出中文。
本教程操作環(huán)境:Windows10系統(tǒng)、PHP8.1版、DELL G3電腦
php json數(shù)據(jù)中文亂碼問題怎么辦?
解決php轉(zhuǎn)json后的中文亂碼
問題:
在php中讀取數(shù)據(jù)庫的數(shù)據(jù),可以用var_dump / print_r 正確讀出中文數(shù)據(jù),但是轉(zhuǎn)了json格式后,中文數(shù)據(jù)就變成亂碼了類似于 "u5c0fu660e";
解決方法:
在json_encode()方法中添加多一個參數(shù)JSON_UNESCAPED_UNICODE;
例如:json_encode($this->cjarr,JSON_UNESCAPED_UNICODE);
為什么要加JSON_UNESCAPED_UNICODE,查詢后我的理解:
php中的json_encode在處理中文數(shù)據(jù)時會進行編碼,得到類似于 "u5c0fu660e" 的字符串,使得讀取數(shù)據(jù)不便,添加JSON_UNESCAPED_UNICODE后就不用編譯中文碼 Unicode,正常輸出中文
問題代碼:
//讀取所有數(shù)據(jù) public function SelectAll(){ $sql = 'SELECT * FROM `websql`'; mysqli_query($this->link,'set names utf8'); $results = mysqli_query($this->link, $sql); while($row = mysqli_fetch_assoc($results)){ array_push($this->cjarr,$row); } } public function a(){ print_r($this->cjarr);//未轉(zhuǎn)json格式前 echo '<br><br>'; echo json_encode($this->cjarr);//轉(zhuǎn)json格式后 }
登錄后復(fù)制
問題輸出:
解決問題代碼:
//讀取所有數(shù)據(jù) public function SelectAll(){ $sql = 'SELECT * FROM `websql`'; mysqli_query($this->link,'set names utf8'); $results = mysqli_query($this->link, $sql); while($row = mysqli_fetch_assoc($results)){ array_push($this->cjarr,$row); } //添加JSON_UNESCAPED_UNICODE 后解決該問題 $this->jsonCjarr = json_encode($this->cjarr,JSON_UNESCAPED_UNICODE); } public function a(){ print_r($this->cjarr);//未轉(zhuǎn)json格式前 echo '<br><br>'; echo $this->jsonCjarr; //輸出 }
登錄后復(fù)制
解決問題后輸出:
推薦學(xué)習(xí):《PHP視頻教程》