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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,