php json_decode for the contents of a .txt file

Advertisements

When I do the following,

    $res1 = '{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}';
    $res1 = json_decode($res);
    var_dump($res1);

It outputs:

object(stdClass)#289 (2) { ["n"]=> int(2) ["stuff"]=> array(1) { [0]=> object(stdClass)#288 (2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" } } }
    

However, when I save the string $res1 into a .txt file named string.txt with the contents:

'{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}'

I do:

$filename = "path/string.txt";
$res2 = file_get_contents($filename);
$res2 = json_decode($res2);

It outputs:

NULL

How can I use json_decode for $res1 from a .txt file the same way as I can use json_decode for $res1 after declaration?

>Solution :

There are a couple of things you can check to fix this issue:

  • Make sure that the file "string.txt" is located in the correct directory and that the path in the $filename variable is correct.

  • Check if the file "string.txt" is encoded in the correct format. json_decode() expects a UTF-8 encoded string, so make sure that the file is saved in that format.

  • Make sure that the contents of the file "string.txt" are exactly the same as the contents of the $res1 variable. If there are any extra spaces or line breaks, json_decode() will return NULL.

  • Check if there is any syntax error in the json, like missing quotes or commas, if so the json_decode will return NULL.

  • Also, make sure to check the variable name, you are using $res1 in your first example but $res2 in the second example, check if you are using the correct variable.

You can use the function json_last_error() after json_decode() to get the error message, this will give you more information about what is causing the problem.

Leave a ReplyCancel reply