CakeFest 2025 Madrid: The Official CakePHP Conference

Voting

: four minus one?
(Example: nine)

The Note You're Voting On

artistan at gmail dot com
10 years ago
Here is my update to Bob's simple SimpleXML wrapper function.
I noticed his version would turn an empty SimpleXMLElement into an empty array.

<?php
/**
* http://php.net/manual/en/function.simplexml-load-string.php#91564
*
* bool/array unserialize_xml ( string $input [ , callback $callback ] )
* Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
* Returns false on all failure
* Notes:
* Root XML tags are stripped
* Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
* Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
*
* @param $input
* @param null $callback
* @param bool $recurse
* @return array|mixed
*
*/
function unserialize_xml($input, $callback = null, $recurse = false)
{
// Get input, loading an xml string with simplexml if its the top level of recursion
$data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
// Convert SimpleXMLElements to array
if ($data instanceof SimpleXMLElement){
if(!empty(
$data)){
$data = (array) $data;
} else {
$data = '';
}
}
// Recurse into arrays
if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
// Run callback and return
return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>

<< Back to user notes page

To Top