php中json_encode中文編碼的問題

來源:互聯網
上載者:User
實際應用中,當有中文字元時,當直接使用json_encode() 函數會使漢字編碼成”\u***”的形式,自從php5.4起 已經解決這個問題,使用以下方法解決漢字被編碼的問題,json_encode("中文", JSON_UNESCAPED_UNICODE)

例如:'胥'經過json_encode處理後變為'\u80e5',最終的json中中文部分被替換為unicode編碼。我們要解決的就是將對象轉換為json並保證對象內部的中文在json中仍然是以正常的中文出現,現在看來只使用json_encode是不能達到目的的。
  我的解決方案:先將類中的中文欄位進行url編碼(urlencode),然後再對對象進行json編碼(jsonencode),最後url解碼(urldecode)json,即最終的json,裡面的中文依舊是那個中文!
測試代碼如下:

<?php class myClass { public $item1 = 1; public $item2 = '中文'; function to_json() { //url編碼,避免json_encode將中文轉為unicode $this->item2 = urlencode($this->item2); $str_json = json_encode($this); //url解碼,轉完json後將各屬性返回,確保對象屬性不變 $this->item2 = urldecode($this->item2); return urldecode($str_json); } } $c = new myClass(); echo json_encode($c); echo '<br/>'; echo $c->to_json(); echo '<br/>'; echo json_encode($c); echo '<br/>'; echo json_encode('胥'); ?>

程式輸出結果:

{"item1":1,"item2":"\u4e2d\u6587"} {"item1":1,"item2":"中文"} {"item1":1,"item2":"\u4e2d\u6587"} "\u80e5"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.