Tony's ramblings on Open Source Software, Life and Photography

PHP Sessions can't handle SimpleXML data

I've been banging my head against the wall over an error reported in some PHP code I've been writing. For some reason the session would be trashed on the server and on next page load I'd get "Node no longer exists" when I tried to open the session.

It turns out that you can't take a response from a SimpleXML object and store it in a session. You'd think that if you could type "echo $myxml->thisnode" and get a string that it's really a string, but PHP automatically typecasts and converts as needed - except in the case of storing in a session variable.

There's an easy solution. Use explicit typecasting when trying to store an XML result string in a $_SESSION[] variable:

$_SESSION['myinteger'] = (int)$myxml->myinteger;
$_SESSION['mystring'] = (string)$myxml->mystring;

Categories:
Anonymous n00b's picture

What a simple solution ,

What a simple solution , saved me a lot of time as I was contemplating a script rewrite.

Used it to retrieve yahoo contacts

//code
$xml = new SimpleXmlElement($response) ;

foreach ($xml->contact as $contact) {

$_SESSION['contact_yahoo'][] = array('first' => (string)$contact->name->first,
'last' => (string)$contact->name->last,
'email' => (string)$contact->email) ;

}
//

Thanks!

Anonymous's picture

Agreed!

I've been banging my head against the wall on this too. There was some stuff info out there about serialize() but that wasn't working.

Thanks so much!

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <p>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for preventing automated spam submissions. It is case sensitive.
Image CAPTCHA
Enter the characters shown in the image.