The Reality of UTF-8 Encoding in PHP Scripts
You are encountering a classic browser rendering issue: your PHP script outputs valid UTF-8 data, but the user agent assumes it is something else, resulting in garbled characters like "CzÃ��Ã�" instead of readable Polish text. You correctly identified that wrapping the output in HTML and adding a <meta> tag solves the problem for web pages. However, when your script must return pure plain textâperhaps for a CLI tool, an API response without JSON wrapping, or a simple status displayâthe meta tag approach is impossible because there is no document structure to attach it to.
The short answer is that you cannot force a browser to interpret raw text as UTF-8 solely through the PHP file itself if the HTTP headers are missing or incorrect. The browser relies on specific signals before it renders any characters. If those signals are absent, it defaults to legacy encodings like ISO-8859-2 (Windows Central European), which explains why "ó" becomes "ó" and "Å" becomes "�".
To fix this for plain text output, you must explicitly tell the browser what is coming before a single byte is printed. This is handled entirely by HTTP headers, not file encoding or meta tags.
Setting the HTTP Content-Type Header
The primary mechanism browsers use to determine character set is the Content-Type header returned by the server. When your PHP script outputs text, it should send:
header('Content-Type: text/plain; charset=utf-8');
This line must appear before any output (echo or print) occurs in the execution flow. If you echo a space or a newline before this header, PHP sends the headers prematurely, and the instruction is ignored.
For your specific use case where you need plain text, this header is the only way to inform the browser that the following bytes are UTF-8. It overrides the browser's default assumption of legacy encodings. Without this, even if your file on disk is saved as UTF-8, the transmission layer tells the browser "I am sending ISO-8859-2," causing the mojibake you are seeing.
File Encoding vs. HTTP Headers
It is crucial to distinguish between how the file is stored and how it is transmitted. Your source material notes that manually changing the browser encoding to UTF-8 fixes the display. This confirms the data on disk is correct, but the server's response headers are not informing the client of this fact.
If you change your .php file's encoding settings in your editor (e.g., saving as UTF-8), that only affects how the code inside the file is interpreted by the PHP engine. It does not automatically set the HTTP response headers. The server configuration or the PHP script itself must explicitly define the Content-Type.
If you are using a shared hosting environment or a specific web server configuration where you cannot modify the global .htaccess files to add a default charset, the solution remains strictly within the script:
<?php
// Ensure this is the very first line of execution
header('Content-Type: text/plain; charset=utf-8');
// Your logic here
$word = 'kot';
// Fetch data...
// Output plain text directly
echo "Cz��� mowy: rzeczownik\n";
Handling Legacy Browsers and Caching
While the Content-Type header is the standard solution, there are nuances to consider. Older browsers or specific mobile devices might ignore the charset parameter in text/plain responses if they have cached a previous version of the page with a different encoding. In such cases, ensuring the cache headers (Cache-Control: no-cache) are set during development can help verify the fix.
Furthermore, if you are outputting this text inside an HTML context later (even if you don't want to wrap the data in <p> tags), ensure your main layout file also declares charset=utf-8 in its meta tag. While the text/plain header handles the specific response, the surrounding HTML document must be consistent to avoid mixed-content warnings or rendering inconsistencies when the user navigates back from a plain text view to an HTML page.
Why Not Use BOM?
You might consider adding a Byte Order Mark (BOM) to the start of your file. While some legacy systems expect UTF-8-BOM, modern web browsers and HTTP protocols generally do not rely on it for encoding detection; they rely strictly on HTTP headers. Adding a BOM to a plain text response can sometimes cause issues with certain parsers or terminal emulators that expect pure UTF-8 without the marker. Therefore, relying on the Content-Type header is the robust, modern approach.
If you are using Laravel and need to handle this within a controller returning a viewless response, you would typically use the Response facade:
return response($text)->header('Content-Type', 'text/plain; charset=utf-8');
This ensures the header is set regardless of how the script was loaded or executed.
