PHPでjson_decodeするとNULLが返ってきたのでエラーの内容を出してみた

<?php
$json = file_get_contents('path/to/file.json');
$array = json_decode($json, true);
var_dump($array); // NULL

NULL。デコード失敗してるっぽい。
json_last_error を使うと直近のJSONエンコード・デコード処理中に発生したエラーを取得することができる。

<?php
$json = file_get_contents('path/to/file.json');
$array = json_decode($json, true);
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}
echo PHP_EOL;

長い。
ということで今度は json_last_error_msg を使ってみる。

<?php
$json = file_get_contents('path/to/file.json');
$array = json_decode($json, true);
echo json_last_error_msg();
echo PHP_EOL;

エラーの内容が文字列で返ってくる。良い。

だが、実際のところ、これらで原因が特定できないことも結構多いっていうのが。辛い。

PHP: json_last_error - Manual

PHP: json_last_error_msg - Manual