Home > php教程 > php手册 > body text

PHP去除BOM头的方法

WBOY
Release: 2016-06-06 19:48:12
Original
1710 people have browsed it

BOM头是UTF-8来告诉编辑器:我是UTF8编码。它的编码是\xEF\xBB\xBF 但是PHP在设计之初并没有考虑到BOM头的问题,所以在编解码的时候很容易出现问题 比如今天遇到的问题,json_decode,当解码的string有BOM头的时候json_decode就解析失败,返回NULL。(为什么

BOM头是UTF-8来告诉编辑器:我是UTF8编码。它的编码是\xEF\xBB\xBF

但是PHP在设计之初并没有考虑到BOM头的问题,所以在编解码的时候很容易出现问题

 

比如今天遇到的问题,json_decode,当解码的string有BOM头的时候json_decode就解析失败,返回NULL。(为什么不自动检测并去除BOM头呢。。。小吐槽)

试了两种方式能去除掉:

 

$result = trim($result, "\xEF\xBB\xBF");
print_r(json_decode($result, true));
exit;
Copy after login

 

还有一种比较矬:

$result = @iconv("UTF-8", "GBK//IGNORE", $result);
$result = @iconv("GBK", "UTF-8//IGNORE", $result);

print_r(json_decode($result, true));
exit;
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template