Andrew Gorpenko Andrew Gorpenko -3 years ago 136
Javascript Question

Can't json_decode() from file - Syntax error

I am stucked with this problem. Here is my code:


$arr = [
'from_name' => '',
'from_email' => '',
'reply_email' => '',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <>, <$token>', 'Precedence: bulk']

echo 'Var dump array to encode: <br>';


$done = json_encode($arr, JSON_UNESCAPED_UNICODE);

echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";


echo "Starting decoding from file: <br><br>";

$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';

echo 'Var dump variable: <br>';

And here is the output:

enter image description here

And here is JSON file, from which I tried to decode json:

{"from_name":"","from_email":"","reply_email":"","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}

As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.

My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...

Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".

P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).

Answer Source

According to the docs, json_decode() does not take a filename as a parameter, only a string.

If you want to decode JSON from a file you would need to do something like this:

$var = file_get_contents('mailconfig.json');
$var = json_decode($var);

Or, if you have to do this a lot, you could wrap the whole thing in a function:

function file_json_decode($path, $assoc = false){
        $json = file_get_contents($path);
        $result = json_decode($json, $assoc);
    } else {
        $result = null;
    return $result

And then call it like this:

$var = file_json_decode('mailconfig.json', true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download