2

I have an Android app, PHP page and MySql db.
The android app send a string parameter to the server, I use Gson so I know that the Json string is correct.
On server side I store that string of json as Text field.
On web client I take that field from my database and doing json_decode and receives a NULL.
Most of the site written by PHPMAKER 10 so I use it's database connection.

$result="";
$rs->MoveFirst();
if ($rs) {
    $result = $rs->fields[0];
}
$rs->Close();
$extras = json_decode($result, true);

I checked that json in Json validator and it looks fine.

Any ideas why I gets null? (maybe encoding)

EDIT: I did the following check:

echo "<script> var x = {$result}; console.log(x.length)</script>";

Chrome gave the following error:

Uncaught SyntaxError: Unexpected token ILLEGAL 

EDIT 2: If I print that string echo $result and copy that to a variable it works.

NickF
  • 5,637
  • 12
  • 44
  • 75

2 Answers2

3

That happened to me, when there was a UTF-8 BOM at the beginning of the JSON string. JSON is UTF-8 as default, so that BOM seems to be forbidden.

You could use this function to remove it:

//Remove UTF8 Bom

function remove_utf8_bom($text)
{
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}

Taken from here: How to remove multiple UTF-8 BOM sequences before "<!DOCTYPE>"?

Community
  • 1
  • 1
Johann Bauer
  • 2,488
  • 2
  • 26
  • 41
1

I soled the problem:
My json contained breaklines '/r' and '/r/n'.
After removing them everything was fine.

NickF
  • 5,637
  • 12
  • 44
  • 75