简体   繁体   中英

PHP - json_decode from mysql

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.

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>"?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM