0

I am using this function http://mysrc.blogspot.it/2007/02/php-xml-to-array-and-backwards.html to parse an XML to an Array. Very great function. But the strange thing is that if I have the following 2 xml files:

<response>
<company prop1=1>
</company>
<company prop1=2>
</company>
</response>

<response>
<company prop1=1>
</company>
</response>

I got different result. For the first case, I got an array of two elements:

Array(
  int(0) => _a => Array(...)
  int(1) => _a => Array(...)
)

but for the second case I got

  Array (
    _a => Array(...)
  )

which is not an array with indexes as the first case. This complicates parsing. Does anybody have any idea how to modify the code? Regards.

1
  • Can you add the 2nd XML file? Commented Oct 29, 2012 at 9:41

2 Answers 2

1

Let's say you do something like

$result = xml2ary($xml);

Try adding this line after your call to xml2ary():

$result = is_int(reset(array_keys($result))) ? $result : array($result);

This checks if the first key of the result array is an integer (which means that the xml2ary function returned multiple results. If not, it automatically wraps the $result variable in an array(), so that you have the same response format even when only one XML item is parsed.

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

Comments

0

Try using the PHP simplexml class:

http://php.net/manual/en/book.simplexml.php

It's the best way to parse XML with PHP

Comments

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.