2

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
3
  • I''s easy to show than explain. Read the answer i'll delete it in some minutes Commented Jan 27, 2018 at 14:46
  • thanks for the answer Commented Jan 27, 2018 at 14:49
  • You can't decode json one line at a time. Load all json with file_get_contents and then decode. Commented Jan 27, 2018 at 14:54

2 Answers 2

2
$file = "./language/english/english.json";
$data = json_decode(file_get_contents($file), true);
var_dump($data);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.