0

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.

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
Shiji.J
  • 1,561
  • 2
  • 17
  • 31
  • Cannot duplicate. Are you certain that's the data that your script is processing? – Ignacio Vazquez-Abrams Oct 19 '15 at 04:38
  • http://jsonlint.com/ indicates your JSON is perfect. Tried using json_decode and that works wonderfully well. Include your code here and in your code, right before `json_decode($rawjson, true);`, do `echo $rawjson;` and include whatever is echoed out in your post as well. – zedfoxus Oct 19 '15 at 04:41
  • @zedfoxus echo $rawjson; shows exactly the same. If you copy and paste my data, there wont be any problem with the decode. But when use file_get_contents, json_decode won't work – Shiji.J Oct 19 '15 at 14:43
  • Look at the very nice solution provided by Alex. Byte order mark sequence is received along with the JSON when you do file_get_contents. That's why you are having troubles. Alex's solution will get you going. If you continue to have troubles, feel free to post a comment – zedfoxus Oct 19 '15 at 15:10

1 Answers1

2

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;
}
Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42