简体   繁体   中英

Having trouble to decode a JSON

I guess there may be a hidden character inside.

JSON data:

The following response i am getting using this URL

{"request":{"command":"series","series_id":"ng.n3010us3.a"},"data":{"error":"No api_key. For key registration, documentation, and examples see http://www.eia.gov/developer/"}}

What I did:

  1. Use file_get_contents fetch the data from the URL

  2. use json_decode($rawjson,TRUE); to make it as an array. -> ERROR

the json_last_error_message shows 'Syntax Error'

I'm trying to find which character is causing the problem.

As mentioned earlier, the response includes a BOM sequence.
See here more about byte-order-mark.

You can remove it like so:

$j = file_get_contents("http://api.eia.gov/series/?api_key=&series_id=NG.N3010US3.A");

$o = json_decode(remove_bom($j));

var_dump($o);


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

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