Skip to content

Instantly share code, notes, and snippets.

@joshtronic
Created November 25, 2010 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshtronic/714874 to your computer and use it in GitHub Desktop.
Save joshtronic/714874 to your computer and use it in GitHub Desktop.
arrayToXML
<?
/**
* Array to XML
*
* Converts an array into XML tags (recursive).
*
* @access private
* @param array $array array to convert into XML
* @return string generated XML
*/
private function arrayToXML($array, $format = false, $level = 0)
{
if ($level == 0)
{
$xml = '<' . key($array) . '>' . ($format ? "\n" : '') . Utility::arrayToXML(current($array), $format, $level + 1) . '</' . key($array) . '>' . ($format ? "\n" : '');
}
else
{
$xml = '';
if (is_array($array))
{
foreach ($array as $node => $value)
{
// Checks if the value is an array
if (is_array($value))
{
foreach ($value as $node2 => $value2)
{
if (is_array($value2))
{
// Nest the value if the node is an integer
$new_value = (is_int($node2) ? $value2 : array($node2 => $value2));
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '<' . $node . '>' . ($format ? "\n" : '');
$xml .= Utility::arrayToXML($new_value, $format, $level + 1);
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '</' . $node . '>' . ($format ? "\n" : '');
}
else
{
if (is_int($node2))
{
$node2 = $node;
}
// Checks for special characters
if (htmlspecialchars($value2) != $value2)
{
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '<' . $node2 . '><![CDATA[' . $value2 . ']]></' . $node2 . '>' . ($format ? "\n" : '');
}
else
{
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '<' . $node2 . '>' . $value2 . '</' . $node2 . '>' . ($format ? "\n" : '');
}
}
}
}
else
{
// Checks for special characters
if (htmlspecialchars($value) != $value)
{
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '<' . $node . '><![CDATA[' . $value . ']]></' . $node . '>' . ($format ? "\n" : '');
}
else
{
$xml .= ($format ? str_repeat("\t", $level) : '');
$xml .= '<' . $node . '>' . $value . '</' . $node . '>' . ($format ? "\n" : '');
}
}
}
}
}
return $xml;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment