BOM 随机出现在 JSON 回复中
我正在使用 JSON 和 cURL 实现两个服务器之间的通信。问题是,有时 JSON 回复中的开括号之前会附加 BOM(字节顺序标记)。我已经设法修剪它并成功解析 JSON 字符串,但考虑到 JSON 是由我自己的代码生成的,我不知道该 BOM 从哪里来。
我使用 json_encode() 生成回复,并使用 header() + echo 打印它,据我所知,json_decode() 不会生成任何 BOM。相应的 .php 文件以 UTF-8 编码,并且其中没有 BOM(根据 Notepad++)。除了 cURL 之外,我还尝试使用 Chrome 和 python (urllib2) 执行请求。虽然 Chrome 根本不注册任何 BOM,但 Python 经常因此无法解析传入的 JSON。
那么,使用 echo 是否存在一些细微差别,以某种方式产生这样的结果?我应该从哪里开始寻找问题的根源以及解决方案是什么?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也有同样的问题。我从 PHP 输出 json,页面顶部还包含其他类文件。这些文件没有输出任何内容,但是当它们被包含时,我得到的字节顺序标记与包含的文件一样多。因此,如果我有 4 个包含项,那么我的 json 开头也有 4 个 BOM。
我确保包含内容不会打印任何数据,并且 PHP 标记之外没有杂散的回车符。我尝试了“application-json”等标头,但没有任何效果。
最后,我只是在记事本++中打开每个 PHP 文件,转到“编码”并将其从 UTF-8 更改为 ANSI,然后保存。这就是让它工作并返回有效的所有操作。 json。我根本没有对 PHP 进行任何代码更改。
这个解决方案感觉仍然不太理想。由于我们没有从这些包含的文件中输出任何内容,因此不应受到任何影响。
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.
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.
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.