CharsetHelper::toCharset¶
(PHP 7 >= 7.4.0, PHP 8)
CharsetHelper::toCharset — Convert data from one encoding to another
Description¶
public static CharsetHelper::toCharset(
mixed $data,
string $to = CharsetHelper::ENCODING_UTF8,
string $from = CharsetHelper::ENCODING_ISO,
array $options = []
): mixed
Converts data (string, array, or object) from one character encoding to another. This method recursively processes arrays and objects, converting all string values while preserving the data structure.
Parameters¶
data:
The data to convert. Can be a string, array, or object. Arrays and objects are processed recursively.
to:
Target encoding. Use one of the CharsetHelper encoding constants (e.g., CharsetHelper::ENCODING_UTF8).
from:
Source encoding. Use CharsetHelper::AUTO for automatic detection, or specify an encoding constant.
options:
Optional array of conversion options:
normalize(bool, default: true): Apply Unicode NFC normalizationtranslit(bool, default: true): Transliterate unmappable charactersignore(bool, default: true): Skip invalid byte sequencesencodings(array): List of encodings for auto-detection
Return Values¶
Returns the converted data in the same type as the input (string, array, or object).
Errors/Exceptions¶
Throws InvalidArgumentException if the encoding is not in the allowed list.
Examples¶
Example #1 Basic string conversion¶
<?php
use Ducks\Component\Component\EncodingRepair\CharsetHelper;
$latin = "Café";
$utf8 = CharsetHelper::toCharset($latin, CharsetHelper::ENCODING_UTF8, CharsetHelper::ENCODING_ISO);
echo $utf8; // Café (UTF-8)
Example #2 Array conversion with auto-detection¶
<?php
use Ducks\Component\Component\EncodingRepair\CharsetHelper;
$data = ['name' => 'José', 'city' => 'São Paulo'];
$utf8Data = CharsetHelper::toCharset($data, CharsetHelper::ENCODING_UTF8, CharsetHelper::AUTO);
print_r($utf8Data);
Example #3 Custom conversion options¶
<?php
use Ducks\Component\Component\EncodingRepair\CharsetHelper;
$result = CharsetHelper::toCharset($data, 'UTF-8', 'ISO-8859-1', [
'normalize' => false,
'translit' => true,
'ignore' => true
]);
See Also¶
- CharsetHelper::toUtf8 — Convert data to UTF-8
- CharsetHelper::toIso — Convert data to ISO-8859-1
- CharsetHelper::detect — Detect charset encoding