dongzhuang6417 2012-10-16 08:10
浏览 116
已采纳

用PHP解析XML。 重复的节点名称

I am parsing xml file with simplexml_load_file() function. I have problem when i meet two nodes with same name. My XML file structure is:

<company>
    <name>Test Co</name>
    <link href="link1" rel="self"/>
    <link href="link2" rel="www"/>
</company>

And here is the code:

$parametrs = simplexml_load_file("my.xml");
foreach ($parametrs->company as $param ) {
    echo $param->name;    
}

How can i echo link2 from each company?

  • 写回答

4条回答 默认 最新

  • douhun8647 2012-10-16 08:23
    关注
    <?php
    $xml = '<?xml version="1.0" ?>
    <company>
    <name>Test Co</name>
    <link href="link1" rel="self"/>
    <link href="link2" rel="www"/>
    </company>';
    
    
    $parameters = new SimpleXmlElement($xml);
    
    echo (string)$parameters->link[1]['href'];  // note you must cast here!
    

    This will output 'link2' (without quotes around it).

    Also, you may want to do some checking up front that these elements exist, but I'll leave that up to you as it's outside the scope of the question ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部