wpa coder wpa coder - 4 months ago 10
JSON Question

can't get array value with file_get_contents() , but work with local file

JSON link: http://vgmdb.info/album/79?format=json

Code I have tried:

$string = file_get_contents("http://vgmdb.info/album/79?format=json");
$json_a=json_decode($string,true);
$getit = $json_a['release_price']['price'];
echo $getit ;


But I get a blank result. Then I try to download the file and upload to my server:

$string = file_get_contents("jsonfile.json");
$json_a=json_decode($string,true);
$getit = $json_a['release_price']['price'];
echo $getit ;


Its show the price value. So how to get price value without download the json file first?

Answer

I tried in localhost and I got:

Warning: file_get_contents(http://vgmdb.info/album/79?format=json): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

This is an hint, so you should always enable your errors when you debug your code.

A http 500 code is an internal error of that server. I just tried to add an User-Agent to the request, and it worked:

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "User-Agent: Mozilla/5.0\r\n"
  )
);

$string = file_get_contents("http://vgmdb.info/album/79?format=json", false, stream_context_create($options));
$json_a=json_decode($string,true);
$getit = $json_a['release_price']['price'];
echo $getit ;