What are the best practices for handling character encoding in PHP?

Character encoding issues can arise when working with different languages and character sets in PHP. To handle character encoding properly, it is important to consistently use UTF-8 encoding throughout your application. This can be achieved by setting the correct encoding in your PHP files, database connections, and HTTP headers.

// Set UTF-8 encoding for PHP files
header('Content-Type: text/html; charset=utf-8');

// Set UTF-8 encoding for database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

// Set UTF-8 encoding for HTTP headers
header('Content-Type: text/html; charset=utf-8');