Search code examples
phpjsonjsondecoder

json_decode() returns null, even though file_get_contents() works perfectly, even though json is valid


Hi everyone i am reading some data from a txt-file with php using

file_get_contents('../../Datafiles/allThreads.txt');

this returns the following string

[{"OP":"ding","threadName":"","content":"","ID":6}]

when i try to vaildate with lint, I have no issues, so the json is valid.

But the problem is that when i call json_decode it keeps returning null:

$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');

Why is this happening? im following all the rules?


Solution

  • You can do it like:

    //storing json contents in a variable.
    $json_contents = file_get_contents('../../Datafiles/allThreads.txt');
    
    //decode json
    $currentThreadasList = json_decode($json_contents, TRUE)
    

    Edit-1:

    Have you tried the following:

    $currentThreadasList = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);