php JSON_encode not working

json_encode() function returns "false" when the encode fails and a "false" result does not appear in an echo or print. See: http://php.net/manual/en/function.json-encode.php The best way to handle such problems would be using the json_last_error_msg() method and performing an action according to the found error. See: http://php.net/manual/en/function.json-last-error-msg.php. An example would be:

$show_json = json_encode($output , JSON_FORCE_OBJECT);
if ( json_last_error_msg()=="Malformed UTF-8 characters, possibly incorrectly encoded" ) {
    $show_json = json_encode($API_array, JSON_PARTIAL_OUTPUT_ON_ERROR );
}
if ( $show_json !== false ) {
    echo($show_json);
} else {
    die("json_encode fail: " . json_last_error_msg());
}

The thing is, if the problem was an encoding character, it will no be shown. Just hope that character is not essential for your work or if you can find the mismatch input in a zigazillion string list, correct it. Other types of errors can be found here: http://php.net/manual/en/json.constants.php. Just apply the if statement and correction for the error you find.

I hope this helps someone.


Thanks to @awiebe I found the exact error. It's

Malformed UTF-8 characters, possibly incorrectly encoded

Thank you all, I found a solution from an another question. 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel


I would like to refer you about this issue, on link I suggest you use a json_encode wrapper like this :

function safe_json_encode($value){
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
    $encoded = json_encode($value, JSON_PRETTY_PRINT);
} else {
    $encoded = json_encode($value);
}
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        return $encoded;
    case JSON_ERROR_DEPTH:
        return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_STATE_MISMATCH:
        return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_CTRL_CHAR:
        return 'Unexpected control character found';
    case JSON_ERROR_SYNTAX:
        return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_UTF8:
        $clean = utf8ize($value);
        return safe_json_encode($clean);
    default:
        return 'Unknown error'; // or trigger_error() or throw new 
Exception();
}
}


function utf8ize($mixed) {
if (is_array($mixed)) {
    foreach ($mixed as $key => $value) {
        $mixed[$key] = utf8ize($value);
    }
} else if (is_string ($mixed)) {
    return utf8_encode($mixed);
}
return $mixed;
}

And after define these function you can use it direct,

echo safe_json_encode($response);