json_encode Chinese becomes null_PHP tutorial

WBOY
Release: 2016-07-20 11:15:10
Original
938 people have browsed it

今天在使用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>?>
Copy after login

输出结果:

<span string</span>(27) "{"id":"123456","name":null}"
Copy after login
“联想”变成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>?>
Copy after login
<?<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>?>
Copy after login

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

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

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440228.htmlTechArticle今天在使用php时掉进了一个坑里,折腾了好久。在使用json_encode时,如果数组中存在中文,该中文输出为null。示例代码: ? = ('id'='123456','n...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template