dongzhuang6417 2012-10-16 16: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 16: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条)

报告相同问题?

悬赏问题

  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用