#46517 [Opn]: SimpleXML inconsistent behaviour with multiple XML nodes

From: Date: Tue, 11 Nov 2008 11:15:52 +0000
Subject: #46517 [Opn]: SimpleXML inconsistent behaviour with multiple XML nodes
References: 1  Groups: php.doc.bugs 
Request: Send a blank email to doc-bugs+get-1484@lists.php.net to get a copy of this message
ID: 46517 Updated by: jani@php.net Reported By: sites at hubmed dot org Status: Open -Bug Type: SimpleXML related +Bug Type: Documentation problem Operating System: * PHP Version: 5CVS, 6CVS (2008-11-11) New Comment: This explains what happens quite good: http://vega.rd.no/article/simplexml-not-that-simple Documentation is a bit vague about this though. Reclassified. Previous Comments: ------------------------------------------------------------------------ [2008-11-07 16:03:21] sites at hubmed dot org Actually, it seems that using foreach($xml->item) works the same whether there's one item or multiple, so it's possible to work around this using the following: ========== $items = array(); foreach ($xml->item as $item) $items[] = $item; ========== That seems to always produce an array of the appropriate objects. ------------------------------------------------------------------------ [2008-11-07 15:30:19] sites at hubmed dot org Description: ------------ This is a duplicate of bug 45023, which is marked as bogus but needs reopening. I'm seeing the same problem with the latest CVS version: PHP 5.2.7RC2-dev (cli) (built: Nov 7 2008 15:02:08) Mac OS 10.5.5 libxml2 2.6.30 At the moment, it's not possible to check whether a SimpleXML element is an array or an object and iterate appropriately (as foreach() will iterate over both an array and an object). Reproduce code: --------------- $xml = simplexml_load_string('<root><item>a</item><item>b</item></root>'); print_r($xml); foreach ($xml->item as $item) print "\n" . 'Item: ' . (string) $item; print "\n"; print'Type: ' . gettype($xml->item); print "\n"; print is_array($xml->item) ? 'Is an array' : 'Not an array'; print "\n"; print_r($xml->item); print_r($xml->item[1]); Expected result: ---------------- gettype($xml->item) should return 'array', and is_array($xml->item) should return true. $xml->item should retrieve the whole array, not just the first item. Actual result: -------------- SimpleXMLElement Object ( [item] => Array ( [0] => a [1] => b ) ) Item: a Item: b Type: object Not an array SimpleXMLElement Object ( [0] => a ) SimpleXMLElement Object ( [0] => b ) ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=46517&edit=1

« previous php.doc.bugs (#1484) next »