note 104479 added to function.unserialize
| From: | chris at colourlovers dot com | Date: | Fri, 17 Jun 2011 00:31:56 +0000 |
| Subject: | note 104479 added to function.unserialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180634@lists.php.net to get a copy of this message | ||
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this
out:
This will traverse $data looking for any children which are instances of SimpleXMLElement, and will
run ->asXML() on them, turning them into a string and making them serializable. Other data will
be left alone.
<?php
function exportNestedSimpleXML($data) {
if (is_scalar($data) === false) {
foreach ($data as $k => $v) {
if ($v instanceof SimpleXMLElement) {
$v = str_replace(" ","\r",$v->asXML());
} else {
$v = exportNestedSimpleXML($v);
}
if (is_array($data)) {
$data[$k] = $v;
} else if (is_object($data)) {
$data->$k = $v;
}
}
}
return $data;
}
$data = array (
"baz" => array (
"foo" => new stdClass(),
"int" => 123,
"str" => "asdf",
"bar" => new SimpleXMLElement('<?xml version="1.0"
encoding="UTF-8"?><foo>bar</foo>'),
)
);
var_dump($data);
/*array(1) {
["baz"]=>
array(4) {
["foo"]=>
object(stdClass)#3 (0) {
}
["int"]=>
int(123)
["str"]=>
string(4) "asdf"
["bar"]=>
object(SimpleXMLElement)#4 (1) {
[0]=>
string(3) "bar"
}
}
}*/
var_dump(exportNestedSimpleXML($data));
/*array(1) {
["baz"]=>
array(4) {
["foo"]=>
object(stdClass)#3 (0) {
}
["int"]=>
int(123)
["str"]=>
string(4) "asdf"
["bar"]=>
string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
}
}
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 71.237.209.126
----
Manual Page -- http://www.php.net/manual/en/function.unserialize.php
Edit -- https://master.php.net/note/edit/104479
Del: integrated -- https://master.php.net/note/delete/104479/integrated
Del: useless -- https://master.php.net/note/delete/104479/useless
Del: bad code -- https://master.php.net/note/delete/104479/bad+code
Del: spam -- https://master.php.net/note/delete/104479/spam
Del: non-english -- https://master.php.net/note/delete/104479/non-english
Del: in docs -- https://master.php.net/note/delete/104479/in+docs
Del: other reasons-- https://master.php.net/note/delete/104479
Reject -- https://master.php.net/note/reject/104479
Search -- https://master.php.net/manage/user-notes.php