PHP fix: Cannot use object of type DOMNodeList as array

Fix php error Cannot use object of type DOMNodeList as array. Use ->item() instead of array access.

<?php
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
 
$nodes = $xpath->query('//path/to/something');
 
// Instead of this:
$var1 = $nodes['0'];
$var2 = $nodes['1'];
$var3 = $nodes['2'];
 
// Use this:
$var1 = $nodes->item(0);
$var2 = $nodes->item(1);
$var3 = $nodes->item(2);
Did this help you? Please let me know with a comment. Thank you
Posted .

3 comments (RSS)

  1. anonymous

    Very helpful!

  2. anonymous

    Very helpful! too

  3. anonymous

    Very helpful! too too

Leave a comment