1

I want to save a piece of XML code in the customer session. So far I tried with the following code.

// Get customer session. 
$customerSession = Mage::getSingleton('customer/session');

// $xml contains a piece of XML code.
$xml= new SimpleXMLElement($xml);
$customerSession->setSegmentList($xml);

But I'm getting the following error.

String could not be parsed as XML

Can anyone suggest how to resolve this? How can I save XML piece of code in customer session?

2

You cannot save objects in session. Well you can but it's a bit complicated. You have to serialize them first and make sure that all the objects within an object are serilizable.
But in your case it's easier.
You can save it in session as a string.
Then just convert it to SimpleXMLElement after reading it.

$xml = '<root><node>text</node></root>';
$customerSession->setSegmentList($xml);

and later when you need it.

$xml = $customerSession->getSegmentList($xml);
$xml = new SimpleXMLElement($xml);
//apply modifications to the xml object if needed.  
//then if you need to save it again in session...
$xml = $xml->asXML(); //turn to string again
$customerSession->setSegmentList($xml);
  • Thank you for the quick response. I'm getting an API response as XML. And I want to convert that xml to a string. I tried to cast it. But getting null. Is there a better way of casting xml to string? – Sukeshini Sep 25 '14 at 8:53
  • That depends entirely on how the api response type. If it's a simple xml it should already be text. But if it's an object type that contains an xml it should have a way of converting it to string. – Marius Sep 25 '14 at 9:18
  • It's a SimpleXMLElement Object – Sukeshini Sep 25 '14 at 9:35
  • then it should work with $xml->asXML(): php.net/manual/en/simplexmlelement.asxml.php – Marius Sep 25 '14 at 9:43
  • Thanks a lot Marius. Yes.. It was the solution. Worked perfectly :) – Sukeshini Sep 25 '14 at 10:52
0

another option would be to serialize your XML. In PHP you can always easily serialize/unserialize objects to store them as text.

$xml=new SimpleXMLElement($xml);
$customerSession->setSegmentList(serialize($xml));

later on when retrieving

$xml=unserialize($customerSession->getSegmentList());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.