XML to Array

I am trying to get a consistent array from my XML API result. The problem I am running into is when a parent has one vs multiple children. I get the XML into an array and I expect to loop thru the foreach [posts][post] -> $thispost show all the posts. When I use the first and display $thispost[‘ID’] I get an error because the foreach loop iterates thru the ID and title and not each post. How do I get it to consistently create an array where the [posts][post] is an array of posts?

Example XML vs resulting Arrays.


<posts>
   <post>
       <ID>1</ID>
       <title>First</title>
   </post>
</posts>

Resulting [posts] Array


Array
(
    [post] => Array
        (
              [ID] => 1
              [title] => First
        )
)

VS


<posts>
   <post>
       <ID>1</ID>
       <title>First</title>
   </post>
   <post>
       <ID>2</ID>
       <title>Second</title>
   </post>
</posts>

Resulting [Posts] Array


Array
(
    [post] => Array
        (
            [0] => Array
                (
                     [ID] => 1
                     [title] => First
                )
            [1] => Array
                (
                     [ID] => 2
                     [title] => Second
                )
        )
)

I think I figured out the answer by modifying the xml_2_array function I am using. Added the $forceArray=array() and added a check where the array indicates. New Code below.


### Returns array from XML url data
function xmlstr_to_array($xmlstr,$forceArray=array()) {
  $doc = new DOMDocument();
  $doc->loadXML($xmlstr);
  return domnode_to_array($doc->documentElement,$forceArray);
}
function domnode_to_array($node,$forceArray) {
  $output = array();
  switch ($node->nodeType) {
   case XML_CDATA_SECTION_NODE:
   case XML_TEXT_NODE:
    $output = trim($node->textContent);
   break;
   case XML_ELEMENT_NODE:
    for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
	
		$child = $node->childNodes->item($i);

		$v = domnode_to_array($child);
		if(isset($child->tagName)) {
			$t = $child->tagName;
			if(!isset($output[$t])) {
				$output[$t] = array();
			}
			$output[$t][] = $v;
		}
		elseif($v) {
			$output = (string) $v;
		}
    }
	
    if(is_array($output)) {
		
		if($node->attributes->length) {
			$a = array();
			foreach($node->attributes as $attrName => $attrNode) {
				$a[$attrName] = (string) $attrNode->value;
			}
			$output['@attributes'] = $a;
		}
		foreach ($output as $t => $v) {
 ------>        	if(!in_array($t, $forceArray)&&is_array($v) && count($v)==1 && $t!='@attributes') {
				$output[$t] = $v[0];
			}
		}
    }
   break;
  }
  return $output;
}



Error!

CHANGE


$v = domnode_to_array($child);

TO


$v = domnode_to_array($child,$forceArray);