Question

I'm outputting some multi-lingual data from my database into a JSON object, but the output isn't showing foreign characters, it just shows question marks even though I have the header charset set to utf8 as such:

header('Content-Type: application/json; charset=utf-8');

When I look at the data in phpMyAdmin, it shows the characters correctly. Is there something I'm doing wrong?

Here is the PHP code that is formatting the JSON output:

$numRows = new stdClass();

$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($stmt = $mysqli->prepare($query)) {
    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();
    $numRows->cc = $stmt->num_rows;

    /* close statement */
    $stmt->close();
}
$mysqli->close();

$count = 0;
$dataCountryCodes = '{';
    $mysqli = dbiConnect();
    $query = "SELECT * FROM country_codes";
    if ($result = $mysqli->query($query)) {
        while($row = $result->fetch_assoc()){
            $count++;
            $rowData = new stdClass();
            $rowData->code = $row['code'];
            $rowData->name = $row['name'];
            $dataCountryCodes = $dataCountryCodes.'"'.$rowData->code.'": {"Code":"'.$rowData->code.'","Country":"'.$rowData->name.'"}';

            if ($count != $numRows->cc) {
                $dataCountryCodes = $dataCountryCodes.',';
            }
        }
    }
    $mysqli->close();
$dataCountryCodes = $dataCountryCodes.'}';
if ($returnCountryCodes == 1) {
    return $dataCountryCodes;
} else {

    header('Content-Type: application/json; charset=utf-8');
    echo ($dataCountryCodes);
}

This is what I am getting:

{"AE": {"Code":"AE","Country":"United Arab Emirates (???????? ???????? ????????)"}}

This is what I got when it was hand coded, this would render fine after I translated the JSON to HTML:

{"AE": {"Code":"AE","Country":"United Arab Emirates (الإمارات العربيّة المتّحدة)"}}
Was it helpful?

Solution

You didn't show dbiConnect function. Check it and try using SET NAMES 'UTF8' after connecting to MySQL:

$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
    die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}

/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $con->error);
}

As the manual says:

SET NAMES indicates what character set the client will use to send SQL statements to the server... It also specifies the character set that the server should use for sending results back to the client.

OTHER TIPS

try this:

$mysqli = dbiConnect();
$mysqli->query("set names utf8")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top