PHP json encode errors

"Malformed UTF-8 characters, possibly incorrectly encoded"

Detection

  1. use json_last_error()
$mainJsonString =  json_encode($mainJsonObj);
//echo "<pre>".print_r($mainJsonString, true)."</pre>";
if ( json_last_error() !== JSON_ERROR_NONE) {
    die( "error parsing data: check if symbols like single quote has come inside the data to parse");
}
  1. use JSON_THROW_ON_ERROR
try {  
  $mainJsonString =  json_encode($mainJsonObj, JSON_THROW_ON_ERROR, 512 );  
}  
catch (\JsonException $exception) {  
  die($exception->getMessage()); // displays "Syntax error"  
}

Solutions

  1. use mb_convert_encoding

eg:

$arrayItem->__FAV_LIST_TITLE__ = mb_convert_encoding($selectResult[$i]['display_title'], 'UTF-8', 'UTF-8');
$arrayItem->__FAV_LIST_SHORT_DESCRIPTION__ = mb_convert_encoding($selectResult[$i]['short_description'], 'UTF-8', 'UTF-8');
  1. use $mysqli->set_charset("utf8");
    eg:

    $this->conn->set_charset("utf8");
  2. use json_encode($text, JSON_INVALID_UTF8_SUBSTITUTE);