json_decode returns JSON_ERROR_SYNTAX but online formatter says the JSON is OK
Solution 1:
I faced the same issue, actually there are some hidden characters unseen and you need to remove it. Here's a global code that works for many cases:
<?php
$checkLogin = file_get_contents("http://yourwebsite.com/JsonData");
// This will remove unwanted characters.
// Check http://www.php.net/chr for details
for ($i = 0; $i <= 31; ++$i) {
$checkLogin = str_replace(chr($i), "", $checkLogin);
}
$checkLogin = str_replace(chr(127), "", $checkLogin);
// This is the most common part
// Some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
// here we detect it and we remove it, basically it's the first 3 characters
if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) {
$checkLogin = substr($checkLogin, 3);
}
$checkLogin = json_decode( $checkLogin );
print_r($checkLogin);
?>
Solution 2:
Removing the BOM
(Byte Order Mark) is often-times the solution you need:
function removeBOM($data) {
if (0 === strpos(bin2hex($data), 'efbbbf')) {
return substr($data, 3);
}
return $data;
}
You shouldn't have a BOM, but if it's there, it is invisible so you won't see it!!
see W3C on BOM's in HTML
use BOM Cleaner if you have lot's of files to fix.