0

I have a strange case of a member of an object that is displayed as type 'Array' in print_r or var_dump, but that is seen as an object by PHP.

Here is what var_dump displays when I do var_dump( $xml);

object(SimpleXMLElement)#84 (3) {
  ["report_metadata"]=>
  object(SimpleXMLElement)#85 (5) {
   ...
  }
  ["policy_published"]=>
  object(SimpleXMLElement)#87 (6) {
  ...
  }
  ["record"]=>
  array(2) {
    [0]=>
    object(SimpleXMLElement)#86 (3) {

But when I do echo gettype($xml->record), it displays 'object', when record is supposed to be an array as displayed in the dump above.

count() on $xml->record does return 2.

I am a bit clueless here, because sometimes record is an array and sometimes it's an object and I would like to detect this using is_array, but it doesn't work.

Here is my code :

$xml = simplexml_load_string( $xml_content);  
var_dump($xml);  

echo gettype($xml->record);  
echo count( $xml->record);  

// Make sure $records is an array  
if (is_array($xml->record)) {   
    $records = $xml->record;  
}  
else {  
    $records = array( $xml->record);  
}  

Thank you so much in advance for your help!

Zlash
  • 1
  • 1
  • SimpleXML is a bit special, you can not always rely on type information you get in dumps. But even on objects, you should be able to iterate using a standard foreach loop. Or you can also try and explicitly cast it into an array, https://stackoverflow.com/a/2726556/1427878 – CBroe May 11 '22 at 10:35

0 Answers0