Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML returns an object instead of a string

Tags:

php

simplexml

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?

like image 582
bcmcfc Avatar asked Nov 29 '25 09:11

bcmcfc


2 Answers

Cast it to a string (or an int) to get the contents of the <SESSIONID> tag:

$this->sessionId = (string) $obj->Body->RESULT->SESSIONID;
like image 65
nickb Avatar answered Dec 01 '25 22:12

nickb


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();
like image 28
AreaEuro Avatar answered Dec 02 '25 00:12

AreaEuro