Si vous êtes intéressés à la conversion récursive ISO-8859-1 encodés en UTF-8,
utiliser un refactor est une façon de le faire.
(Je l'ai utilisé pour préparer certains ISO-8859-1 pour les tableaux json_encode. Notez que pour que cela fonctionne, vos valeurs et tableaux associatifs également vos clés doivent être ISO-8859-1-codés.)
- Code: Tout sélectionner
<?php
/**
* (Recursively) utf8_encode each value in an array.
*
* @param array $array
* @return array utf8_encoded
*/
function utf8_encode_array($array)
{
if (is_array($array))
{
$result_array = array();
foreach($array as $key => $value)
{
if (array_type($array) == "map")
{
// encode both key and value
if (is_array($value))
{
// recursion
$result_array[utf8_encode($key)] = utf8_encode_array($value);
}
else
{
// no recursion
if (is_string($value))
{
$result_array[utf8_encode($key)] = utf8_encode($value);
}
else
{
// do not re-encode non-strings, just copy data
$result_array[utf8_encode($key)] = $value;
}
}
}
else if (array_type($array) == "vector")
{
// encode value only
if (is_array($value))
{
// recursion
$result_array[$key] = utf8_encode_array($value);
}
else
{
// no recursion
if (is_string($value))
{
$result_array[$key] = utf8_encode($value);
}
else
{
// do not re-encode non-strings, just copy data
$result_array[$key] = $value;
}
}
}
}
return $result_array;
}
return false; // argument is not an array, return false
}
/**
* Determines array type ("vector" or "map"). Returns false if not an array at all.
* (I hope a native function will be introduced in some future release of PHP, because
* this check is inefficient and quite costly in worst case scenario.)
*
* @param array $array The array to analyze
* @return string array type ("vector" or "map") or false if not an array
*/
function array_type($array)
{
if (is_array($array))
{
$next = 0;
$return_value = "vector"; // we have a vector until proved otherwise
foreach ($array as $key => $value)
{
if ($key != $next)
{
$return_value = "map"; // we have a map
break;
}
$next++;
}
return $return_value;
}
return false; // not array
}
?>

