Search code examples
phpsimplexml

Trouble extracting string from SimpleXMLElement in PHP


I am trying to extract the string value from the SimpleXMLElement below (which has been returned from a SOAP endpoint) but I'm having no joy:

object(SimpleXMLElement)[476]
  public 'return' => string 'ff7ecc8af5ecaaba412c3b453c5f65f1' (length=32)

I have tried casting the entire object as a string, it just returns empty, I've tried treating 'return' as key, etc. This is such a simple task, can't believe it's got me stumped.


Solution

  • Your problem, somewhat hidden in the question, is that the element name is a reserved word, so you can't use the ordinary syntax:

    $value = (string)$xml->return; # SYNTAX ERROR
    

    The solution is to use braces and quotes around the name, which allows you to use reserved words or characters:

    $value = (string)$xml->{'return'};