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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器