【问题标题】:Can't json_decode() from file - Syntax error无法从文件中读取 json_decode() - 语法错误
【发布时间】:2017-08-16 20:29:21
【问题描述】:

我被这个问题困住了。这是我的代码:

<?php 

$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team@rosresurs.net',
'reply_email' => 'reply@rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support@rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];

echo 'Var dump array to encode: <br>';
var_dump($arr);

//Encoding

$done = json_encode($arr, JSON_UNESCAPED_UNICODE);

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

//Decoding

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>';
var_dump($var);

这是输出:

这是 JSON 文件,我尝试从中解码 json:

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

如您所见,我的数组包含 UTF-8 符号,因此我使用 JSON_UNESCAPED_UNICODE 选项对它们进行了编码。但是当我尝试解码(从文件)时,它失败了。但是当我尝试从编码变量 $done 解码时,它工作得很好。

我的 json 文件包含相同的 $done 输出(从浏览器复制并粘贴到文件中)。 json_last_error 说这是一个语法错误。但是没有人……

我还将文件中的 json 字符串粘贴到在线 json 语法验证服务,它返回“一个有效的 JSON 字符串”。

附:我做了很多回声助手(见截图),所以你可以快速解决问题(比如开始编码和解码点)。

【问题讨论】:

    标签: javascript php json syntax


    【解决方案1】:

    根据文档,json_decode() 不接受文件名作为参数,只接受字符串。

    如果您想从文件中解码 JSON,您需要执行以下操作:

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

    或者,如果你必须经常这样做,你可以将整个事情包装在一个函数中:

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

    然后这样称呼它:

    $var = file_json_decode('mailconfig.json', true);
    

    【讨论】:

    • 嗯。这很简单:)谢谢:)
    【解决方案2】:

    您在错误的参数上调用json_decode。第一个参数是 JSON 数据,而不是文件名!所以如果你想从一个文件中解析 JSON,你可以写

    json_decode(file_get_contents('mailconfig.json'), true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多