OTARIKI OTARIKI - 3 years ago 264
PHP Question

How to convert DOMNodeList object into array

I have this code:

$dom = new DOMDocument();
$names = $dom->getElementsByTagName('name');

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 Source

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:


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

$array = (array)new Foo;
array(1) {

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download