Last active
June 25, 2019 16:59
-
-
Save thbighead/fddc09451b8e5bb6dcf7ade2eed41042 to your computer and use it in GitHub Desktop.
Métodos para transformar arrays em XMLs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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