What are the best practices for handling special characters like "ß" in PHP when retrieving and displaying data from databases?
Special characters like "ß" can cause encoding issues when retrieving and displaying data from databases in PHP. To handle these characters properly, it is important to ensure that the database connection is set to use the correct character set (e.g., UTF-8) and that the PHP script also specifies the same character set when interacting with the database. Additionally, using functions like utf8_encode() or utf8_decode() can help convert special characters to the correct encoding for display.
// Set the character set for the database connection
$mysqli->set_charset("utf8");
// Specify the character set for the PHP script
header('Content-Type: text/html; charset=utf-8');
// Retrieve data from the database
$result = $mysqli->query("SELECT * FROM table");
// Display the data with proper encoding
while ($row = $result->fetch_assoc()) {
echo utf8_encode($row['column_name']);
}