I am having a lot of issues getting a response from json using php. The code below echos nothing and I have no idea why. I need to be able to access all points of that json file individually through functions.
file.json
{
"file":{
"name": "File Name",
"description": "This is a file!",
"license": "glp-2.0",
"version": "1.1.1",
"author": [{
"name": "Author Name",
"email": "name@domain.com"
}],
"require": [{
"php": ">= 5.2.4",
"myslq": ">= 5.0",
}]
}
}
localhost/data.php
define('PATH', 'http://domain.com/json/');
function test(){
$json = file_get_contents( PATH."file.json" );
$data = json_decode($json,true);
echo $data['file']['name'];
}
test();
define('PATH', 'http://domain.com/json/');
function test(){
$json = file_get_contents( PATH."file.json" );
$data = json_decode(preg_replace('/,\s*([\]}])/m', '$1', utf8_encode($json)),true);
echo $data['file']['name'];
}
test();
preg_replace('/,\s*([]}])/m', '$1', utf8_encode($json)) In bold above fixed my issue.
It's a good idea to use a debugger or to do some debug print outs. Try:
$json = file_get_contents( PATH."file.json" );
var_dump($json);
$data = json_decode($json,true);
var_dump($data)
Now you can see if file_get_contents or json_decode doesn't work.
A much better option is to use a debugger while developing software in order to find failures easily. Get more information on: http://xdebug.org/.