OTARIKI OTARIKI - 1 month ago 14
PHP Question

How to convert DOMNodeList object into array

I have this code:

$dom = new DOMDocument();
$dom->load('file.xml');
$names = $dom->getElementsByTagName('name');


Now,
$names
is DOMNodeList object, I need to convert this object into an array,

$names = (array)$names;
var_dump($names); // empty array


The above code does not work and returns an empty array, why?

Answer

Why doesn't (array) work? Because a DOMNodeList object has only one property, length, and it's of integer type:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Since a DOMNodeList implements the Traversable interface, it's fairly easy to create the array yourself:

$array = array();
foreach($names as $node){
    $array[] = $node;
}

Edit: I've removed the initial explanation because it doesn't apply here. What the manual means is that properties with numeric names are passed to the array but cannot be read:

<?php

class Foo{
    public function __construct(){
        $this->{123} = 456;
    }
}

$array = (array)new Foo;
var_dump($array);
var_dump($array['123']);
array(1) {
  ["123"]=>
  int(456)
}

Notice: Undefined offset: 123 in D:\tmp\borrame.php on line 11
NULL

The explanation is probably more on the line that DOMNodeList is not a user object created with PHP code but a builtin object defined in C, so different rules apply.