簡體   English   中英

無法從文件json_decode()-語法錯誤

[英]Can't json_decode() from file - Syntax error

我陷入這個問題。 這是我的代碼:

 <?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選項對它們進行了編碼。 但是當我嘗試解碼(FROM FILE)時,它失敗了。 但是,當我嘗試從編碼變量$ done解碼時,它可以完美工作。

我的json文件包含相同的$ done輸出(從瀏覽器復制並粘貼到文件)。 json_last_error說這是語法錯誤。 但是沒有人...

我也將json字符串從文件粘貼到在線json語法驗證服務中,並返回“有效的JSON字符串”。

PS我做了很多回聲助手(請參見屏幕截圖),因此您可以快速解決問題(例如開始編碼和解碼點)。

您在錯誤的參數上調用json_decode 第一個參數是JSON數據,而不是文件名! 因此,如果您想從文件中解析JSON,則可以編寫

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

根據文檔, 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM