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?

asked Sep 25, 2014 at 6:33

2 Answers 2

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);
answered Sep 25, 2014 at 6:40
5
  • 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? Commented Sep 25, 2014 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. Commented Sep 25, 2014 at 9:18
  • It's a SimpleXMLElement Object Commented Sep 25, 2014 at 9:35
  • then it should work with $xml->asXML(): php.net/manual/en/simplexmlelement.asxml.php Commented Sep 25, 2014 at 9:43
  • Thanks a lot Marius. Yes.. It was the solution. Worked perfectly :) Commented Sep 25, 2014 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());
answered May 20, 2016 at 17:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.