PHP ob_iconv_handler() Function

Definition
In PHP, ob_iconv_handler() is an output buffer callback that converts the buffered output from the internal encoding to the output encoding.
You pass its name to ob_start(), and PHP converts the page when the buffer is flushed.
Syntax
Call ob_iconv_handler() with the values you need. Start with this line.
ob_start("ob_iconv_handler");
| Call | What it does |
|---|
ob_start("ob_iconv_handler") | Starts a buffer that converts its output. |
ob_end_flush() | Sends the converted output. |
The target comes from the iconv.output_encoding setting, or default_charset if that is empty.
Library declarations
ob_iconv_handler(string $contents, int $status): string
Parameters
| Parameter | Description |
|---|
| contents | Required. The buffered output. |
| status | Required. A bit mask of PHP_OUTPUT_HANDLER_* flags. PHP sets this when the handler runs. |
Return Value
| Return Value | Description |
|---|
| string | The converted contents. |
PHP Examples
Example 1 — Start the Handler
Use the handler with ob_start(). With the default UTF-8 settings the text does not change.
<?php
ob_start("ob_iconv_handler");
echo "Hello";
ob_end_flush();
How It Works
- Start a buffer. Pass the handler name as a string.
- Echo text. It goes into the buffer, not to the screen.
- Flush the buffer. The handler converts the text first.
- Both encodings are UTF-8, so the text stays the same.
Example 2 — Convert UTF-8 to Latin-1
Set the two encodings, then call the handler yourself and show the bytes.
<?php
error_reporting(E_ALL & ~E_DEPRECATED);
ini_set("iconv.internal_encoding", "UTF-8");
ini_set("iconv.output_encoding", "ISO-8859-1");
$converted = ob_iconv_handler("café", PHP_OUTPUT_HANDLER_FINAL);
echo bin2hex($converted), PHP_EOL;
How It Works
- Hide the deprecation notices for the two settings.
- Set the input to UTF-8 and the output to ISO-8859-1.
- Call the handler with the text and a status flag.
- Show the bytes.
e9 is é in ISO-8859-1.
Frequently Asked Questions
ob_iconv_handler() is an output buffer callback. It converts buffered output from the internal encoding to the output encoding.
ob_iconv_handler(string $contents, int $status): string. You normally pass its name to ob_start().
It comes from the iconv.output_encoding setting, or from default_charset when that setting is empty.
Yes. It sets the charset in the Content-Type header so the browser reads the converted text correctly.
No. If your whole page is UTF-8, no conversion is needed.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful