symfony/polyfill-iconv
Native PHP polyfill for the iconv extension, providing implementations of common iconv functions (except ob_iconv_handler). Useful when iconv isn’t available, ensuring consistent character set conversion behavior across environments.
Installation: Add the package via Composer:
composer require symfony/polyfill-iconv
No additional configuration is required—it auto-loads and replaces missing iconv functions.
First Use Case: Test basic encoding conversion in a Laravel controller or service:
use Symfony\Polyfill\Iconv\Iconv;
// Example: Convert UTF-8 to ASCII, ignoring unsupported characters
$text = "Café";
$converted = iconv('UTF-8', 'ASCII//IGNORE', $text); // Outputs: "Cafe"
Verify Functionality:
Disable ext-iconv locally to test polyfill behavior:
php -d extension=iconv.ini artisan tinker
Then run:
iconv('UTF-8', 'UTF-16', 'Hello'); // Should work without native extension
Key Functions Supported:
iconv(), iconv_strlen(), iconv_strpos(), iconv_substr()iconv_mime_encode(), iconv_mime_decode()//TRANSLIT, //IGNORE).Automatic Fallback:
The polyfill replaces missing iconv functions without manual checks. Use native syntax:
// Works in all environments (with or without ext-iconv)
$cleaned = iconv('UTF-8', 'ASCII//TRANSLIT', $userInput);
Laravel-Specific Integrations:
public function rules()
{
return [
'name' => 'string|max:255|iconv:UTF-8/ASCII//IGNORE', // Custom validator
];
}
$content = file_get_contents($path);
$utf8Content = iconv('ISO-8859-1', 'UTF-8', $content);
Database Interactions: Normalize charset for queries or migrations:
// In a migration or model observer
$normalized = iconv('Windows-1252', 'UTF-8', $legacyData);
API Responses: Standardize encoding for internationalized responses:
return response()->json([
'message' => iconv('UTF-8', 'UTF-8//IGNORE', $userMessage),
]);
CI/CD Pipeline: Force polyfill usage in test environments:
# .github/workflows/tests.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- run: php -d extension=iconv.ini -r "echo 'Native iconv available';"
- run: php -d extension=-iconv.ini vendor/bin/phpunit
Legacy System Migration:
Gradually replace mbstring with iconv:
// Before: mbstring
$length = mb_strlen($text, 'UTF-8');
// After: iconv (polyfill-compatible)
$length = iconv_strlen($text, 'UTF-8');
Multilingual Content Processing: Chain encoding operations for complex workflows:
$processed = iconv('UTF-8', 'UTF-16', $text)
-> iconv('UTF-16', 'ASCII//TRANSLIT', $text);
Str facade for encoding utilities:
// app/Helpers/StrHelper.php
if (!class_exists('Str')) {
require __DIR__.'/../../vendor/laravel/framework/src/Illuminate/Support/Str.php';
}
class StrHelper extends Str {
public static function iconv($string, $inCharset, $outCharset)
{
return iconv($inCharset, $outCharset, $string);
}
}
// app/Providers/AppServiceProvider.php
public function boot()
{
if (!extension_loaded('iconv')) {
$this->app->bind('encoding', function () {
return new class {
public function convert($string, $from, $to) {
return iconv($from, $to, $string);
}
});
});
}
}
// tests/Feature/EncodingTest.php
public function test_iconv_polyfill()
{
if (extension_loaded('iconv')) {
$this->markTestSkipped('Native iconv available; skip polyfill test.');
}
$result = iconv('UTF-8', 'ASCII//IGNORE', 'Café');
$this->assertEquals('Cafe', $result);
}
Unsupported Functions:
ob_iconv_handler: Not supported. Use mbstring output buffering instead:
ob_start('mb_output_handler');
iconv_get_encoding: Fall back to mb_internal_encoding():
$encoding = mb_internal_encoding();
Transliteration Quirks:
$arabic = iconv('UTF-8', 'ASCII//TRANSLIT', 'محمد');
// May output: "mohammad" (varies by PHP version)
Performance Bottlenecks:
iconv. Profile with:
composer require blackfire/php
vendor/bin/blackfire run php artisan your:command
mbstring for high-throughput tasks.Environment Mismatches:
default_charset in php.ini or .env:
DEFAULT_CHARSET=UTF-8
ext-iconv in Dockerfile for testing:
RUN docker-php-ext-disable iconv
False Positives:
function_exists('iconv'): Always returns true (even with polyfill). Use:
if (extension_loaded('iconv')) {
// Native extension available
}
Encoding Artifacts:
? or garbled characters. Debug with:
var_dump(bin2hex($string)); // Hex dump to identify encoding issues
// Force UTF-8 normalization
$clean = iconv('UTF-8', 'UTF-8//IGNORE', $dirty);
Polyfill Detection:
if (strpos(iconv('UTF-8', 'UTF-8', 'test'), 'Symfony') !== false) {
// Polyfill is active
}
Log Encoding Warnings:
iconv usage:
// app/Http/Middleware/CheckEncoding.php
public function handle($request, Closure $next)
{
if (!extension_loaded('iconv')) {
Log::warning('Using iconv polyfill; consider enabling ext-iconv in production.');
}
return $next($request);
}
Configuration:
.env: Set default charset:
APP_CHARSET=UTF-8
default_charset matches:
default_charset = "UTF-8"
Extension Points:
iconv:
function custom_iconv($inCharset, $outCharset, $string)
{
$result = iconv($inCharset, $outCharset, $string);
// Add custom logic (e.g., logging, validation)
return $result;
}
Performance Optimization:
$cache = new ArrayCache();
$cached = $cache->remember("iconv_{$in}_{$out}_{$string}", 3600, function()
How can I help you explore Laravel packages today?