I need to get a language file stored in a json file. The problem is that it always returns null, even when the document encoding in the file is UTF-8.
$file = fopen("./language/english/english.json", "r");
while(!feof($file))
{
$lines = fgets($file);
$data = json_decode($lines, true);
var_dump($data);
}
fclose($file);
english.json
{
"english": {
"hello_world": "test"
}
}
returns
NULL NULL NULL NULL NULL
$file = "./language/english/english.json";
$data = json_decode(file_get_contents($file), true);
var_dump($data);
Problem is that you are trying to decode a line at a time (inside line reading while loop). Use file_get_contents() to get all json data and decode after that. As getting correctly formed JSON files may be tricky, I would suggest some error checking along the line too.
Something like this:
$filename = "./language/english/english.json";
if (!file_exists($filename)){
print('No file!');
die();
}
$data = json_decode(file_get_contents($filename), true);
// check if there was a json decode error
if (json_last_error()){
print('JSON error: '.json_last_error_msg());
die();
}
print('<pre>');
print_r($data);