Skip to content

Instantly share code, notes, and snippets.

@thbighead
Last active June 25, 2019 16:59
Show Gist options
  • Save thbighead/fddc09451b8e5bb6dcf7ade2eed41042 to your computer and use it in GitHub Desktop.
Save thbighead/fddc09451b8e5bb6dcf7ade2eed41042 to your computer and use it in GitHub Desktop.
Métodos para transformar arrays em XMLs
/**
* Transforma array em XML. Este método trata os casos de repetição para chaves com
* valores de arrays sequenciais onde o objetivo é criar múltiplas tags com estas chaves.
*
* @param array $data
* @param SimpleXMLElement $xml_data
*/
function array_to_xml(array $data, SimpleXMLElement $xml_data)
{
foreach ($data as $key => $value) {
if (is_array($value)) {
if (is_assoc($value)) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
foreach ($value as $v) {
if (is_array($v)) {
$subnode = $xml_data->addChild($key);
array_to_xml($v, $subnode);
}
else $xml_data->addChild("$key", htmlspecialchars("$v"));
}
}
} else {
$xml_data->addChild("$key", htmlspecialchars("$value"));
}
}
}
/**
* Testa se um array é associativo ou sequencial. Arrays vazios são tratados como sequenciais.
*
* @param array $arr
* @return bool true caso seja associativo
*
*/
function is_assoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment