0

I am pretty new to PHP and hope someone here can help me with the following.

I have a simpleXML object that looks as follows (shortened):

<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>

How can I convert this into an array using PHP that has the following structure (hard-coded for demoing)?

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

Many thanks for any help with this, Mike.

1 Answer 1

1

It can be done by iterating over the history elements like so:

$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;
}

Outputs

Array
(
    [item1] => 53
    [item2] => 20
    [item3] => 7
    [item4] => 4
    [item5] => 2
    [item6] => 2
    [item7] => 1
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this is great ! - How do I get the commas added between the different items ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.