Current Location: Home> Latest Articles> Use mysqli::get_charset in REST API development to ensure correct JSON encoding

Use mysqli::get_charset in REST API development to ensure correct JSON encoding

M66 2025-05-28

When developing REST APIs, it is crucial to correctly encode and transfer data. Especially when writing APIs using MySQL databases and PHP, we often need to ensure that the data read from the database can be correctly encoded into JSON format and transferred to the client correctly. If there is a problem with encoding, it may lead to garbled Chinese characters or other abnormal display phenomena. This article will explain how to ensure the correctness of JSON encoding when using MySQL databases through the mysqli::get_charset method.

1. Problem background

When our REST API gets data from a MySQL database and returns it to the client, data exchange is often performed in JSON format. If the database character set does not conform to the PHP encoding, especially when special characters such as Chinese are returned, garbled may appear. Common garbled problems are usually encoding conversion problems caused by inconsistent character sets. We need to make sure the database connection uses the correct character set to avoid these problems.

2. Use mysqli::get_charset to ensure character set consistency

In MySQL databases, we usually use the UTF-8 character set to store and transfer text data. In PHP, we use the mysqli extension to interact with the MySQL database. The mysqli::get_charset method can help us get the character set of the current database connection and ensure that we are using the UTF-8 character set.

Sample code:

 <?php
// Create a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check if the connection is successful
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Get the character set of the currently connected
$current_charset = $mysqli->get_charset();

// Output the current character set
echo "Current character set: " . $current_charset->charset;

// Set the character set to UTF-8(If not set)
if ($current_charset->charset !== 'utf8') {
    if (!$mysqli->set_charset("utf8")) {
        die("Character set setting failed: " . $mysqli->error);
    }
}

// Execute a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

// Check the query results
if ($result->num_rows > 0) {
    $data = array();

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    // return JSON Format data
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
} else {
    echo "No data";
}

// Close the database connection
$mysqli->close();
?>

In the above code, first we get the character set of the current database connection through mysqli::get_charset . If the current character set is not utf8 , then use the set_charset("utf8") method to set the character set to utf8 . This ensures that the data we read from the database will not have garbled problems when transmitted.

3. Why choose UTF-8?

UTF-8 is a multi-byte character encoding method that can represent almost all language character sets in the world. In web development, UTF-8 is widely used because it supports the storage and exchange of multilingual data. Especially in the REST API, the data transmitted usually includes characters from a variety of different languages, so it is important to ensure that the database and application use consistent UTF-8 encoding.

4. Special options in JSON encoding

In PHP, json_encode is a function used to encode PHP arrays or objects into JSON strings. However, json_encode will escape some characters by default, such as non-ASCII characters. To ensure that the output JSON string can display Chinese characters normally without being escaped, we can use the JSON_UNESCAPED_UNICODE option.

Sample code:

 echo json_encode($data, JSON_UNESCAPED_UNICODE);

Using the JSON_UNESCAPED_UNICODE option can prevent Chinese characters from being escaped into Unicode encoding (such as \u4e2d\u56fd ), thereby improving the readability of JSON data.

5. URL domain name replacement

In your request, if there is a part of the code that uses URL, you need to replace the domain name with m66.net . For such a requirement, we can dynamically replace the domain name when processing URL fields in the database.

Sample code:

 // Assume that it is read from the database URL data
$url = "http://example.com/api/resource";

// use str_replace Replace domain name
$updated_url = str_replace("example.com", "m66.net", $url);

// Output updated URL
echo $updated_url;

In the above code, we use the str_replace function to replace the domain name part in the original URL with m66.net to ensure that the URL address meets the requirements.

6. Summary

It is important to ensure that JSON encoding is correct in the REST API, especially when it comes to multilingual data. By using the mysqli::get_charset method to check and set the character set of the database to UTF-8 , we can avoid the garbled problem caused by inconsistent character encoding. At the same time, using the JSON_UNESCAPED_UNICODE option of json_encode can ensure that the Chinese characters in the JSON data are displayed correctly, rather than being escaped into Unicode characters. Finally, with a simple string replacement operation, you can ensure that the domain name part in the URL meets specific requirements.