Home  >  Article  >  Backend Development  >  json_encode Chinese becomes null_PHP tutorial

json_encode Chinese becomes null_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:15:10934browse

今天在使用php时掉进了一个坑里,折腾了好久。 在使用json_encode时,如果数组中存在中文,该中文输出为null。   示例代码:

<?<span php
  </span><span $brand</span> = <span array</span>('id'=>'123456','name'=>'联想'<span );
  </span><span var_dump</span>(json_encode(<span $brand</span><span ));
</span>?>

输出结果:

<span string</span>(27) "{"id":"123456","name":null}"
“联想”变成null了。 使用下面这个函数解决了此问题。
<?<span php
  </span><span function</span> gbk2utf8(<span $data</span><span ){
    </span><span if</span>(<span is_array</span>(<span $data</span><span )){
      </span><span return</span> <span array_map</span>('gbk2utf8', <span $data</span><span );
    }
    </span><span return</span> <span iconv</span>('gbk','utf-8',<span $data</span><span );
  }
</span>?>
<?<span php
  </span><span $brand</span> = <span array</span>('id'=>'123456','name'=>'联想'<span );
  </span><span var_dump</span>(json_encode(gbk2utf8(<span $brand</span><span )));
</span>?>

在json_encode之前做一下gbk2utf8转码,此时输出正确结果。

<span string</span>(37) "{"id":"123456","name":"\u8054\u60f3"}"

\u8054\u60f3 为“联想”的unicode码,浏览器会自动转换成文字。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440228.htmlTechArticle今天在使用php时掉进了一个坑里,折腾了好久。在使用json_encode时,如果数组中存在中文,该中文输出为null。示例代码: ? = ('id'='123456','n...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn