I have some XML that looks like this:
<Body>
<RESULT>
<SUCCESS>true</SUCCESS>
<SESSIONID>42</SESSIONID>
<SESSION_ENCODING>;jsessionid=42</SESSION_ENCODING>
</RESULT>
</Body>
SimpleXML parses it, in this way:
$obj = simplexml_load_string($xmlStringAsAbove);
$this->sessionId = $obj->Body->RESULT->SESSIONID;
and the result is this:
[sessionId:protected] => SimpleXMLElement Object
(
[0] => 42
)
What I need is this:
[sessionId:protected] => 42
How can I achieve this?
Cast it to a string (or an int) to get the contents of the <SESSIONID> tag:
$this->sessionId = (string) $obj->Body->RESULT->SESSIONID;
In my experience, SimpleXMLElement can be a pain when you need a value instead of an object.
As per the previous answer, you can cast the XML part you want, or use one of the following methods:
From the ops example, to get an integer you can use intval():
$this->sessionId = intval($obj->Body->RESULT->SESSIONID);
As of (PHP 5 >= 5.3.0, PHP 7) you can also use the SimpleXMLElement::__toString method to get a string;
https://www.php.net/manual/en/simplexmlelement.tostring.php
$this->sessionIdasString = $obj->Body->RESULT->SESSIONID->__toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With