dongmei2956
dongmei2956
2014-08-26 16:40
浏览 34

从XML结构获取指定参数的数组

I have xml structure like this:

<categories>
   <category>
     <id>1</id>
     <name> category name </name>
          . 
          . 
          . 
   </category>
   <category>
     <id>2</id>
     <name> category name </name>
          . 
          . 
          . 
   </category> 
   <category>
     <id>3</id>
     <name> category name </name>
          .
          . 
          .       
   </category> 
   .
   . 
</categories>

And using PHP SimpleXML to convert xml to an array, but i have question: Is there some simple way to get one dimensional array only of category ids (like array(1, 2, 3, ... )) using some PHP function?

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duan19780629
    duan19780629 2014-08-26 16:45
    已采纳

    There is no built-in function to do that through SimpleXML directly. But it's not that hard to get the IDs with a foreach loop :

    $categories = new SimpleXMLElement($my_xml);
    
    foreach ($categories->category as $cat) {
      $arr[] = (string) $cat->id;
    }
    
    点赞 评论

相关推荐