Ok, so I have a JSON file that looks like this:
There are nine such objects in the JSON array. Now I want to access the data in my model file. The problem is I followed the method recommended all over the internet, yet I’m met with an error.
// Model used to access the partyinfo JSON file
$jsonString = file_get_contents('partyinfo.json');
$jsonData = json_decode($jsonString, true);
var_dump($jsonData);
The code.
I validated my JSON file, and it passed with flying colours. When I use the include function, it reads the file verbatim, yet file_get_contents can’t even access it. The two files are the only two files in the model directory.
2
Answers
When you don’t specify the path to a file, the places PHP looks are different for including code vs reading a file, and both are subject to runtime changes which are hard to reason about.
It is pretty much always better to use an absolute path, constructed from something which can’t change at runtime. The best for this is the magic constant
__DIR__
, which resolves to the directory of the PHP file where you write it.So rather than
file_get_contents('partyinfo.json')
, usefile_get_contents(__DIR__ . '/partyinfo.json')
or to look in a "neighbouring" directory, you can use..
to go "up a level" e.g.file_get_contents(__DIR__ . '/../data/partyinfo.json')
Different to
include('partyinfo.json')
the functionfile_get_contents('partyinfo.json')
does not use theinclude_path
directive unless you pass the second parameter astrue
:Given you were able to access the file with the
include
statement, passingtrue
as second parameter may already suffice.However, I personally would not want to rely on the include path to open data files, but instead would provide the full pathname to the directory entry of the JSON Text file to open.
You can easily construct the absolute pathname by prepending the basename with the
__DIR__
magic constant (PHP 5.3 – June 30, 2009) and a directory separator character (/
slash/solidus on Linux and Windows — but not MS-DOS) given it has its entry in the same directory as the partyjson.php file:If you use a PHP version that is of the year of JSON (2001), you can obtain the pathname to the JSON Text file by using the
__FILE__
magic constant (PHP 3 – June 6, 1998) and thedirname()
function to obtain the directory name. It always contains an absolute path, whereas in older versions (mind PHP 4 and lower versions, this is long ago!) it contained a relative path under some circumstances. Ineval()
,__FILE__
contains path, line and description (since PHP 4.1).Magic constants in PHP are not case sensitive, but they are commonly written in uppercase letters.