I am getting an error in my project: Malformed UTF-8 characters, possibly incorrectly encoded. I've been searching this forum and so far I can only find results where users were using MySQL. We have a pervasive database and to my knowledge have to use ODBC to connect to run queries in my web apps. In order to fix the above error, my research says I'll have to set the charset to utf8 though I'm unsure of how to do that with the ODBC connection. Below is my code with what I've tried commented out:
<?php
$conn = new PDO ('odbc:xxx','xxx','xxx');//I tried adding charset=utf8 to the odbc here but that failed
$qry = "select distinct name_customer from v_customer_master";
$sql = $conn->query($qry);
//$sql->set_charset("utf8");
//$custName = array();
while($row = $sql->fetch((PDO::FETCH_ASSOC))){
$custName[] = [$row['name_customer']];
//array_push($custName,$row['name_customer']);
}
//print_r($custName);
header('Content-Type: application/json; charset=utf-8');//this changed the error to SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
//but developer tools still shows the Malformed UTF-8 error.
echo (json_encode($custName,JSON_UNESCAPED_UNICODE));
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script
?>
Adding a line with mb_convert_encoding() before pushing the value into the array fixed the issue.
while($row = $sql->fetch((PDO::FETCH_ASSOC))){
$row['name_customer'] = mb_convert_encoding($row['name_customer'], 'UTF-8', 'UTF-8');
$custName[] = $row['name_customer'];
}