dongyou9373 2012-10-09 13:45
浏览 78
已采纳

如何使用php simpleXML获取多个XML元素属性

I have this XML

<STOREITEMS>
  <CREATED value="Tue Oct 9 5:30:01 BST 2012">
    <CATEGORY id="442" name="Hen And Stag Nights"></CATEGORY>
    <CATEGORY id="69" name="Games"></CATEGORY>
    <CATEGORY id="252" name="Love Zone"></CATEGORY>
    <CATEGORY id="202" name="Spotlight  Items"></CATEGORY>
  </CREATED>
</STOREITEMS>

I need to get the Category - name attribute with PHP

So far I have this

$xml = simplexml_load_file("http://www.dropshipping.co.uk/catalog/xml_id_multi_info.xml");

foreach($xml->CATEGORY['name']->attributes() as $category)    
{    
    echo $category; 
}

This however returns Fatal error: Call to a member function attributes() on a non-object

Any ideas? Thank you.

  • 写回答

1条回答 默认 最新

  • doueta6642 2012-10-09 14:10
    关注

    The CATEGORY nodes are nested inside the CREATED node, so you'd need to access it there, and accessing CATEGORY['name']->attributes() makes no sense, since that would try to access non-existent attributes on the name attribute of the first CATEGORY node.

    So do you want to retreive the name attribute values of all CATEGORY nodes, or all CATEGORY nodes, or maybe only those CATEGORY nodes that have a name attribute?

    All CATEGORY nodes:

    foreach($xml->CREATED->CATEGORY as $category)
    {
        echo $category['name'] . '<br />';
    }
    

    Only the CATEGORY nodes name attributes:

    foreach($xml->xpath('//CATEGORY/@name') as $name)
    {
        echo $name . '<br />';
    }
    

    Only the CATEGORY nodes that have a name attribute:

    foreach($xml->xpath('//CATEGORY[@name]') as $category)
    {
        echo $category['name'] . '<br />';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!