BOM随机出现在JSON回复中 [英] BOM randomly appears in JSON reply

查看:122
本文介绍了BOM随机出现在JSON回复中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON和cURL实现两台服务器之间的通信.问题是,有时在JSON回复中的方括号之前会附加BOM(字节顺序标记).我已经设法修剪它并成功解析了JSON字符串,但是考虑到JSON是由我自己的代码生成的,所以我不知道BOM表是从哪里来的.

I'm implementing communication between two servers using JSON and cURL. The problem is, that sometimes there's BOM (byte order mark), appended before opening bracket in JSON reply. I've managed to trim it and successfully parse JSON string, but considering that JSON is generated by my own code, I've no idea, where does that BOM come from.

我正在使用json_encode()生成回复,并使用header()+ echo进行打印,据我所知,json_decode()不会生成任何BOM.相应的.php文件以UTF-8编码,并且其中没有BOM(根据Notepad ++).除了cURL,我还尝试过使用Chrome和python(urllib2)执行请求.尽管Chrome根本不注册任何BOM,但是python经常会因此而无法解析传入的JSON.

I'm using json_encode() to generate reply and header() + echo to print it, an as far as I cant tell, json_decode() does not produce any BOMs. Corresponding .php files are encoded in UTF-8 and have no BOM in them (according to Notepad++). Apart from cURL, I've also tried to perform requests using Chrome and python (urllib2). While Chrome does not register any BOM at all, python regularly fails to parse incoming JSON because of it.

那么,使用回声是否有些细微之处,以某种方式产生了这样的结果?我应该从哪里开始寻找问题的根源以及可能的解决方案?

So, is there some nuance in using echo, that somehow produces such a result? Where should I start looking for the source of the problem and what may be the solution?

推荐答案

我遇到了同样的问题.我从PHP输出json,并且页面顶部还包含其他类文件.这些文件什么也不输出,但是当包含它们时,我得到的字节序标记与包含文件一样多.因此,如果我有4个包含,则在json的开头也有4个BOM.

I had the same problem. I was outputting json from PHP and there were other class files included at the top of the page. These files output nothing, but when they were included I was getting as many Byte Order Marks as I had included files. So if I had 4 includes, I also had 4 BOMs at the start of my json.

我确保include文件没有打印任何数据,并且PHP标记之外没有杂散的回车符.我尝试使用诸如"application-json"之类的标题,但没有任何效果.

I made sure the includes were not printing any data and there were no stray carriage returns outside the PHP tags. I tried headers such as "application-json", etc., but nothing worked.

最后,我只是简单地在notepad ++中打开每个PHP文件,转到编码",然后将其从UTF-8更改为ANSI,然后保存.并返回有效的json.我根本没有对PHP进行任何代码更改.

In the end, I simply opened each PHP file in notepad++, went to "Encoding" and changed it from UTF-8 to ANSI, then saved. That was all it took to get it working and returning valid json. I made no code changes to the PHP at all.

此解决方案仍然感觉不理想.由于我们不从包含的文件中输出任何内容,因此不会受到任何影响.

This solution still feels less than ideal. Since we are not outputting anything from those included files there shouldn't be anything affected.

这篇关于BOM随机出现在JSON回复中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆