PHP:将simpleXML对象转换为二维数组

时间:2014-04-09 09:54:23

标签: php xml arrays xml-parsing simplexml

我对PHP很陌生,希望有人可以帮我解决以下问题。

我有一个simpleXML对象,如下所示(缩写):

<ranks>
  <history>
    <ranking>1</ranking>
    <groupName>currentMonth<item>item1</item><groupCount>53</groupCount></groupName>
  </history>
  <history>
    <ranking>2</ranking>
    <groupName>currentMonth<item>item2</item><groupCount>20</groupCount></groupName>
  </history>
  <history>
    <ranking>3</ranking>
    <groupName>currentMonth<item>item3</item><groupCount>7</groupCount></groupName>
  </history>
  <history>
    <ranking>4</ranking>
    <groupName>currentMonth<item>item4</item><groupCount>4</groupCount></groupName>
  </history>
  <history>
    <ranking>5</ranking>
    <groupName>currentMonth<item>item5</item><groupCount>2</groupCount></groupName>
  </history>
  <history>
    <ranking>6</ranking>
    <groupName>currentMonth<item>item6</item><groupCount>2</groupCount></groupName>
  </history>
  <history>
    <ranking>7</ranking>
    <groupName>currentMonth<item>item7</item><groupCount>1</groupCount></groupName>
  </history>
</ranks>

如何使用具有以下结构的PHP将其转换为数组(用于演示的硬编码)?

$arr = array("item1"=>"53","item2"=>"20","item3"=>"7","item4"=>"4","item5"=>"2","item6"=>"2","item7"=>"1");

非常感谢Mike的任何帮助。

1 个答案:

答案 0 :(得分:1)

可以通过迭代历史元素来完成:

$obj = simplexml_load_string($xml); // change to simplexml_load_file if needed

$arr = array();

foreach($obj->history as $history){
    $arr[(string)$history->groupName->item] = (int)$history->groupName->groupCount;
}

输出

Array
(
    [item1] => 53
    [item2] => 20
    [item3] => 7
    [item4] => 4
    [item5] => 2
    [item6] => 2
    [item7] => 1
)