3

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?

2 Answers 2

8

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

$this->sessionId = (string) $obj->Body->RESULT->SESSIONID; 
Sign up to request clarification or add additional context in comments.

Comments

2

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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.