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 Answers 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– Sukeshini2014年09月25日 08:53:52 +00:00Commented 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.Marius– Marius2014年09月25日 09:18:25 +00:00Commented Sep 25, 2014 at 9:18
-
It's a SimpleXMLElement ObjectSukeshini– Sukeshini2014年09月25日 09:35:35 +00:00Commented Sep 25, 2014 at 9:35
-
then it should work with
$xml->asXML(): php.net/manual/en/simplexmlelement.asxml.phpMarius– Marius2014年09月25日 09:43:49 +00:00Commented Sep 25, 2014 at 9:43 -
Thanks a lot Marius. Yes.. It was the solution. Worked perfectly :)Sukeshini– Sukeshini2014年09月25日 10:52:43 +00:00Commented Sep 25, 2014 at 10:52
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());
Explore related questions
See similar questions with these tags.