Search code examples
phpsimplexmlvar-dump

Why is var_dump() saying a string is an object?


I'm using an Amazon API to retrieve product information and the response (converted to an object using simplexml_load_string()) looks like this:

SimpleXMLElement Object
(
    [Items] => SimpleXMLElement Object
        (
            [Item] => SimpleXMLElement Object
                (
                    [ASIN] => B00C9WDZIG
                    [ParentASIN] => B00C9WDZIG
                )
        )
)

The output of this:

var_dump($parsed_xml->Items->Item->ASIN);
var_dump($parsed_xml->Items->Item->ParentASIN);

is this:

object(SimpleXMLElement)[3]
  string 'B00C9WDZIG' (length=10)

object(SimpleXMLElement)[4]
  string 'B00C9WDZIG' (length=10)

I'm confused because var_dump() is outputting objects instead of strings. Why is that? Aren't ASIN and ParentASIN string values inside of the third SimpleXMLElement object?

In other words, I expected the output to be:

string 'B00C9WDZIG' (length=10)

string 'B00C9WDZIG' (length=10)

And I'm confused why it wasn't.

Can anyone explain this?


Solution

  • SimpleXML is a chained object. It's deceptive because you can do something like

    echo (string)$xml->tag;
    

    And get the value of something like <tag>value</tag>. But tag is also an instance of SimpleXML because you might need to get the attributes or children still. So var_dump is correct.

    Let me explain further. Here's some sample XML for you

    <xml>
      <mytag>
        <skate>roll</skate>
        <surf>swim</surf>
      </mytag>
    </xml>
    

    When we dump this into SimpleXMLElement(SXE), what we get is an instance of SXE. So the top object is our overall wrapper <xml> and we'll say we dumped that into $xml. The next level down is $xml->mytag. This is ALSO an SXE object. So are $xml->mytag->skate and $xml->mytag->surf. If you do

    var_dump($xml->mytag->surf);
    

    It will tell you that as well. It needs to be this way because let's say we want to modify the XML. We can just jump straight into

    $xml->mytag->addChild('skydive', 'fall');
    echo $xml->asXML();
    

    Which outputs

    <xml>
      <mytag>
        <skate>roll</skate>
        <surf>swim</surf>
        <skydive>fall</skydive>
      </mytag>
    </xml>