Home  >  Article  >  php教程  >  PHP去除BOM头的方法

PHP去除BOM头的方法

WBOY
WBOYOriginal
2016-06-06 19:48:121612browse

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;

 

还有一种比较矬:

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

print_r(json_decode($result, true));
exit;
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