schouk schouk - 1 year ago 107
JSON Question

json_decode returns NULL after webservice call

There is a strange behaviour with

and I can't find a solution:

My php application calls a php web service. The webservice returns json that looks like this:

string(62) "{"action":"set","user":"123123123123","status":"OK"}"

now I like to decode the json in my application:

$data = json_decode($foo, true)

but it returns


I use php5.
The Content-Type of the response from the webservice:
"text/html; charset=utf-8"
(also tried to use
"application/json; charset=utf-8"

What could be the reason?

Answer Source

EDIT: Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as  here.

Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).

string(62) "{"action":"set","user":"123123123123","status":"OK"}"
            This is the UTF-8 BOM

As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download