1

I try to parse xml into arrays. I have got 2 types of incoming data: 1)

<rows>
<item>
<a>A</a>
<b>B</b>
</item>
<item>
<c>C</c>
<d>D</d>
</item>
</rows>

2)

<rows>
<item>
<e>E</e>
<f>F</f>
</item>
</rows>

I create an object of SimpleXMLElement and then convert it in array as in Converting a SimpleXML Object to an Array using first answer. The result in first case is

[ '0' => ['a' => 'A', 'b' => 'B'], '1' => ['c' => 'C', 'd' => 'D']].

The result in second case is ['e' => 'E', 'f' => 'F']

But I need a numeric key in second case [ '0' => ['e' => 'E', 'f' => 'F']]

How to fix it?

2
  • You will have to handle this progrmmatically Commented Mar 5, 2018 at 10:01
  • This may help you Commented Mar 5, 2018 at 12:04

2 Answers 2

1

For your given example, I think you could use array_values which (from the docs):

returns all the values from the array and indexes the array numerically.

$xml = simplexml_load_string($source);
$result = array_values(json_decode(json_encode($xml), true));
var_dump($result);

Will give you:

array(1) {
  [0]=>
  array(2) {
    ["e"]=>
    string(1) "E"
    ["f"]=>
    string(1) "F"
  }
}

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

If you have your e,f array (Which is the output of your second case, but i've generated it here. Just use your XML array from your second case)

$arr1 = array(
    'e' => 'E',
    'f' => 'F',
    'g' => 'G',
    'h' => 'H',
);

you can then do

$arr2 = array_chunk($arr1, 2);

which will give you the output ($arr2):

[0 => ['e' => 'E', 'f' => 'F'], 1=> ['g' => 'G', 'h' => 'H']]

and that will work assuming that you want your sub arrays to always be 2 items in length. You can change that by changing the second parameter of array_chunk().

2 Comments

Not sure if this answers OP's question at all.
They wanted the output of the array to be split into seperate numerically keyed arrays, this does that, but I might have misunderstood the question.

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.