开发者

BOM randomly appears in JSON reply

开发者 https://www.devze.com 2023-04-06 11:33 出处:网络
I\'m implementing communication between two servers using JSON and cURL. 开发者_C百科The problem is, that sometimes there\'s BOM (byte order mark), appended before opening bracket in JSON reply. I\'ve

I'm implementing communication between two servers using JSON and cURL. 开发者_C百科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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号