Ever tried to use json_decode()
to decode some JSON and found that it just returned NULL
, even though the same string passed JSONLint etc? This happened to me on a recent project and I spent literally hours trying to figure out what was causing it.
Just as I’d given up and had started to hack the JSON string by hand (urgh!), I found this tweet:
@rbolgov: @sydlawrence You use non breaking space(charcode = 160) instead of usual space (charcode=32). For PHP it’s big deal.” <– thanks (source)
This was the same reason that my code was failing, here is a quick helper function I used in the project to work around this issue:
function _json_decode($str)
{
$str = str_replace(chr(160), chr(32), $str);
return json_decode($str);
}
Hope this saves others some time, big thanks to Syd Lawrence & Bolgov Roman for the tip!