Converting PHP Arrays from Windows-1250 to UTF-8
When retrieving data from a legacy database using reklamacje or similar tables, you often encounter encoding mismatches that manifest as garbled characters like �. In the specific case of your code snippet, the issue arises because the database returns bytes interpreted as Windows-1250 (CP1250), but your PHP environment expects UTF-8. Simply printing the result with print_r() reveals these artifacts immediately.
The core problem isn't just about changing a string; it's about handling the byte stream correctly before the data enters your application logic. If you attempt to cast the entire array directly using mb_convert_encoding without understanding the internal structure, you risk double-encoding or corrupting binary fields like images stored in BLOBs.
The Correct Conversion Strategy
The most reliable approach is to iterate over the result set and convert each string value individually. You must ensure that only actual text strings are converted, leaving integers, booleans, and database objects untouched. Here is how you can implement this safely:
require_once ('config.php');
require_once ('php/Db.class.php');
require_once ('php/Top.class.php');
$db = new Db(DB_CUSTOM);
$db->connect();
$res = $db->getResult("select first 1 * from reklamacje");
// Iterate over each row in the result array
foreach ($res as $row) {
foreach ($row as $key => $value) {
// Check if the value is a string before converting
if (is_string($value)) {
// Convert from windows-1250 to utf-8
$convertedValue = mb_convert_encoding(
$value,
'UTF-8',
'Windows-1250'
);
// Assign the converted value back to the array
$row[$key] = $convertedValue;
}
}
}
print_r($res);
This method ensures that every string column containing Polish characters (or any other accented European character) is properly re-encoded. The mb_convert_encoding function handles the mapping of bytes from CP1250 to the Unicode space defined by UTF-8.
Why Not Convert at the Database Level?
While fixing the application code works, the ideal solution often lies in the database configuration itself. If your database is configured with a charset that does not match the client connection (e.g., MySQL defaulting to CP1250 while connecting as UTF-8), you will face this issue on every request.
You should check and modify your connection parameters to enforce UTF-8 at the source. For MySQL, this typically involves setting the character_set_client, character_set_connection, and character_set_results variables during the connection handshake. If your Db.class.php allows you to pass configuration options, ensure that utf8mb4 is set as the default for new connections. This prevents the need to manually convert data in PHP every time, reducing overhead and ensuring consistency across different parts of your application.
Handling Binary Data and Performance Considerations
A critical pitfall when applying mb_convert_encoding is ignoring binary columns. If your query selects columns like photo_data or file_content, these contain raw bytes that are not text. Converting binary data as if it were a string will result in garbled output and potential file corruption upon storage.
Always verify column types before conversion. In the loop above, relying on is_string() helps, but for strict environments, you might want to skip known binary columns explicitly or check the database schema metadata. Additionally, processing large datasets row-by-row can introduce latency. If you are dealing with massive result sets, consider fetching data in batches or converting the data at the application layer using stream wrappers if available, though for most standard CRUD operations, the row-by-row approach remains the safest and most maintainable path.
Integration with Modern Frameworks
If you are maintaining legacy code like the snippet above but planning to migrate to a modern stack, frameworks like Laravel provide built-in helpers that abstract this complexity. While your current setup uses custom classes, transitioning to an ORM like Eloquent would allow you to handle encoding via migrations and connection configuration rather than manual loops.
For instance, in a Laravel context, you would configure the config/database.php file to default all connections to utf8mb4. This ensures that even if the underlying storage is legacy, the application layer consistently treats data as UTF-8, rendering manual conversion logic obsolete. However, sticking with your current architecture requires this explicit conversion step to bridge the gap between the database's native encoding and the PHP standard.
Ultimately, the goal is to present clean, readable data to the user. By iterating through string values and applying mb_convert_encoding with the correct source (Windows-1250) and target (UTF-8) specifications, you resolve the � artifacts without breaking your existing application flow.
