du22399 2016-05-30 05: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 05: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部