note 91494 modified in book.simplexml by danbrown
| From: | danbrown@php.net | Date: | Fri, 12 Jun 2009 16:01:38 +0000 |
| Subject: | note 91494 modified in book.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156810@lists.php.net to get a copy of this message | ||
Working fix for the infamous SimpleXML + memcache bug.
Improves code at http://tinyurl.com/bmoon-simplexml
to actually work for arbitrary-depth structures. (Because neither the function nor the
json_decode(json_encode($obj)) hack listed there worked for me.)
There's probably some superfluous code in here that could be improved on -- but it works!
<?php
# convert a structure that may include objects to a pure
# array-based structure (that can be stored in memcache)
# ... includes support for simplexml!
# (nb: may have problems with infinite recursive structs)
function enforce_array($obj) {
$array = (array)$obj;
if(empty($array)) {
$array = '';
}
else {
foreach($array as $key=>$value) {
if(!is_scalar($value)) {
if(is_a($value,'SimpleXMLElement')) {
$tmp = memcache_objects_to_array($value);
if(!is_array($tmp)) {
$tmp = ''.$value;
}
$array[$key] = $tmp;
}
else {
$array[$key] = enforce_array($value);
}
}
else {
$array[$key] = $value;
}
}
}
return $array;
}
?>
--was--
Working fix for the infamous SimpleXML + memcache bug.
Improves code at http://tinyurl.com/bmoon-simplexml
to actually work for arbitrary-depth structures. (Because neither the function nor the
json_decode(json_encode($obj)) hack listed there worked for me.)
There's probably some superfluous code in here that could be improved on -- but it works!
<?
# convert a structure that may include objects to a pure
# array-based structure (that can be stored in memcache)
# ... includes support for simplexml!
# (nb: may have problems with infinite recursive structs)
function enforce_array($obj) {
$array = (array)$obj;
if(empty($array)) {
$array = '';
}
else {
foreach($array as $key=>$value) {
if(!is_scalar($value)) {
if(is_a($value,'SimpleXMLElement')) {
$tmp = memcache_objects_to_array($value);
if(!is_array($tmp)) {
$tmp = ''.$value;
}
$array[$key] = $tmp;
}
else {
$array[$key] = enforce_array($value);
}
}
else {
$array[$key] = $value;
}
}
}
return $array;
}
?>
http://php.net/manual/en/book.simplexml.php