Skip to content

Instantly share code, notes, and snippets.

@oscar-broman
Created September 6, 2012 09:05
Show Gist options
  • Save oscar-broman/3653399 to your computer and use it in GitHub Desktop.
Save oscar-broman/3653399 to your computer and use it in GitHub Desktop.
UTF8 encode array/object structure in PHP
<?php
function utf8_encode_deep(&$input) {
if (is_string($input)) {
$input = utf8_encode($input);
} else if (is_array($input)) {
foreach ($input as &$value) {
utf8_encode_deep($value);
}
unset($value);
} else if (is_object($input)) {
$vars = array_keys(get_object_vars($input));
foreach ($vars as $var) {
utf8_encode_deep($input->$var);
}
}
}
?>
@charliexyx
Copy link

Thanks for the idea, tipochka, but it still does not work. Here is an example for non-working code, since I got no idea how to change the different -Elements. In the follwing example for the line "foreach ($input as $k=>$val)" $k is twice 'bar'. That occurs errors. And foreach by reference is not possible here (Fatal-Error).

$xml_string = "<?xml version='1.0'?><foo><bar><bar_string><![CDATA[example1ÄÖÜ]]></bar_string></bar><bar><bar_string><![CDATA[example2ÄÖÜ]]></bar_string></bar></foo>"

//must be UTF8 to work fine with this function.
$xml = simplexml_load_string($xml_string);

//Now I cannot decode.
$xml_utf8_decoded = Tools::utf8_code_deep($xml, FALSE);

@seba2305
Copy link

thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment