Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'

user761088 picture user761088 · May 19, 2011 · Viewed 30.5k times · Source

I am not sure why this is coming up. I am not serializing the XML, but my array that I created from an RSS feed (note this is just a snippet):

$game_data = array (
    'sysreqos'  => $game->systemreq->pc->sysreqos,
    'sysreqmhz' => $game->systemreq->pc->sysreqmhz,
    'sysreqmem' => $game->systemreq->pc->sysreqmem,
    'sysreqdx'  => $game->systemreq->pc->sysreqdx,
    'sysreqhd'  => $game->systemreq->pc->sysreqhd,
);

Then I serialize it $some_var = serialize($game_data) and write to a text file fputs($fh,$some_var).

But it does not get that far, it errors out on the serialize line:

Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'

Answer

Stefan Gehrig picture Stefan Gehrig · May 19, 2011

You have to cast the XML data to a string because internally they are all SimpleXMLElements.

$game_data = array (
                'sysreqos'       => (string)$game->systemreq->pc->sysreqos,
                'sysreqmhz'      => (string)$game->systemreq->pc->sysreqmhz,
                'sysreqmem'      => (string)$game->systemreq->pc->sysreqmem,
                'sysreqdx'       => (string)$game->systemreq->pc->sysreqdx,
                'sysreqhd'       => (string)$game->systemreq->pc->sysreqhd
            );

Or perhaps a little bit more elegant:

$game_data  = array();
$properties = array('sysreqos', 'sysreqmhz', 'sysreqmem', 'sysreqdx', 'sysreqhd');
foreach ($properties as $p) {
    $game_data[$p] = (string)$game->systemreq->pc->$p;
}