SimpleXML/array duality (like particles & waves)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I am kind of jacked here. I have a SimpleXML object that's been converted to an array. In one of the nodes, for no reason I can see, the array is populated differently if there is only one <order_item> than if there are multiple <order_item>s.

If there is just one, my $order_item array looks like this:
Array
(
    [order_item_product_code] => 1300
    [order_item_description] => 4x8 photo cards (set of 20)
)

But if there are multiple items, I get this:
Array
(
    [0] => SimpleXMLElement Object
        (
            [order_item_product_code] => 1060
            [order_item_description] => 4x5.3 trueDigital print(s)
        )

    [1] => SimpleXMLElement Object
        (
            [order_item_product_code] => 1300
            [order_item_description] => 4x8 photo cards (set of 20)
        )
)

See my problem? I can't foreach through those and process the items in the same way.

In case it matters, here is that snip of what the original XML looks like, it's all good:
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="http://xxxx.com/xxxx"; version="1.0">
  <order_items>
    <order_item>
      <order_item_product_code finish="glossy">1060</order_item_product_code>
      <order_item_description>4x5.3 trueDigital print(s)</order_item_description>
    </order_item>
    <order_item>
      <order_item_product_code finish="glossy">1300</order_item_product_code>
      <order_item_description>4x8 photo cards (set of 20)</order_item_description>
    </order_item>
  </order_items>
</order>

And here is the function I'm using to convert the XML to an array:
function xmlToArray($xml, $isChild = false) {
	if($xml instanceof SimpleXMLElement) {
		$xmlObject = $xml;
	} elseif($isChild) {
		return $xml;
	} else {
		try {
			$xmlObject = new SimpleXMLElement($xml);
		} catch(Exception $e) {
			$string = $e->getMessage();
			throw new Exception('Invalid XML found in ' . __FUNCTION__ . ' function on line '.__LINE__.'.');
		}
	}
	$children = (array)$xmlObject->children();
	if(is_array($children)) {
		if(count($children) == 0) {
			$children = '';
		} else {
			foreach($children as $element => $value) {
				$children[$element] = xmlToArray($value, true);
			}
		}
	}
	return $children;
}

Any suggestions?
-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux