duanan1228 2014-01-09 22:54
浏览 158
已采纳

为什么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 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择