Skip to content

Instantly share code, notes, and snippets.

@nimmneun
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save nimmneun/9ffe5eb912f30e486c2f to your computer and use it in GitHub Desktop.

Select an option

Save nimmneun/9ffe5eb912f30e486c2f to your computer and use it in GitHub Desktop.
Create XML string from array
<?php
/**
* @Author neun
* @since 09.04.2015 21:23
*/
class XMLifier
{
/**
* Regex chars that _dont_ need to be wrapped in CDATA.
* @var string
*/
private static $noCDATA = '\w\s\%.,+\-:';
/**
* Some extra stuff before we get going.
* @param $array
* @param string $noCDATA
* @return string
*/
public static function toXml($array, $noCDATA = null)
{
if (!empty($noCDATA))
{
self::$noCDATA = $noCDATA;
}
return '<?xml version="1.0" encoding="utf-8"?><widgets>' . self::xmlify($array) .'</widgets>';
}
/**
* Expects an n-dimensional array to be transformed into a XML string.
* @param $array
* @return null|string
*/
private static function xmlify($array)
{
$str = null;
foreach ($array as $name => $value)
{
$str .= "<{$name}>";
if (!is_array($value))
{
if (preg_match('/^[' . self::$noCDATA . ']+$/', $value, $m))
{
$str .= $value;
}
else
{
$str .= '<![CDATA[' . $value . ']]>';
}
}
else
{
$str .= self::xmlify($value);
}
$str .= "</{$name}>";
}
return $str;
}
}
/**
* My lovable dummy for testing ...
*/
$dummy =
array(
'eins' => array(
'title' => 'SuperXXL Shirt',
'info' => "That's one friggin awesome shirt there!! <3",
'attributes' => array(
'size' => 'XXL',
'color' => 'blue',
'price' => '9.95',
'discounts' => array(
'spring' => '10%',
'summer' => '5%',
'autumn' => '15%',
'winter' => '20%',
)
)
),
'zwei' => array(
'title' => 'MegaXXS Shirt',
'attributes' => array(
'size' => 'XXS',
'color' => 'green',
'price' => '7.95',
'materials' => array(
'whool' => '50%',
'polyester' => '50%'
)
),
'shipping' => array(
'domestic' => '2.95',
'europe' => '4.95',
'other' => '9.99'
)
),
'drei' => array(
'title' => 'BoringM Shirt',
'attributes' => array(
'size' => 'M',
'color' => 'yellow',
'price' => '8.97',
'some' => array(
'other' => array(
'funny' => array(
'value' => array(
'with' => array(
'crazy' => array(
'deep' => array(
'nesting' => 'lol'
)
)
)
)
)
)
)
)
)
);
header("Content-type:text/xml");
echo XMLifier::toXml($dummy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment