duanan1228
2014-01-09 22:54 阅读 121
已采纳

为什么var_dump()说一个字符串是一个对象?

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dsjlqkbpn029473708 dsjlqkbpn029473708 2014-01-09 22:58

    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>
    
    点赞 2 评论 复制链接分享

相关推荐