du22399 2016-05-30 13:32
浏览 21
已采纳

似乎无法从simpleXML对象中获取字符串

I have my xml file

<names>
    <person>
        <name>John</name>
        <alias>
            <part>Joe</part>
            <part>Foo</part>
        </alias>
    </person>
</names>

which I saved as $xml.

foreach($xml as $person)
    var_dump($person->name);

The above code returns

object(SimpleXMLElement)#7 (1) {
  [0]=>
  string(4) "John"
}

instead of just

string(4) "John"

With the actual return it gives, I would assume adding [0] to the end of the variable would give me the correct return, but it returns the exact same thing. I have tried adding [0], ["0"], ->0, ->"0", and nothing works. The last 2 tries gave me a parse error, while the first 2 gave me the same response as the original.

How can I get the string(4) "John" from inside the object(SimpleXMLElement)?

  • 写回答

1条回答 默认 最新

  • dongsu3654 2016-05-30 13:48
    关注

    That's because the XML is a resource, ie:

    $xml = '<names>
            <person>
                <name>John</name>
                <alias>
                    <part>Joe</part>
                    <part>Foo</part>
                </alias>
            </person>
        </names>';
    
    $parsed = simplexml_load_string($xml);
    
    var_dump($parsed->getName());
    

    Will output names, showing, that the element/layer you are in is named names.

    And so will parsed->person->name give you a resource. If you want to drop the resource and just access the value, you need to convert it to string:

    var_dump((string)$parsed->person->name);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题