Search code examples
phphtmlxmldom

xmlDom Call to a member function item() on a non object


Hi I have a table with rows and columns.

<table>
  <tr>
    <td style="font-size:14px"></td>
  </tr>
  <tr>
    <td background="image.jpg"></td>
  </tr>
</table>

And im using this code to get all the elements with tag name td

$td= $xmlDoc->getElementsByTagName('td'); 

Then looping it to get each td tag through this code

for($i = 0; $i<$td->length; $x++){
   print_r($td->item($i));
}

The problem is when there is a style attribute inside the td tag, i'm getting this error Fatal error: Call to a member function item() on a non-object. But if i remove the style attribute inside the td tag it works.

So this one works:

<table>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td background="image.jpg"></td>
  </tr>
</table>

And this one doesn't

<table>
  <tr>
    <td style="font-size:14px;"></td>
  </tr>
  <tr>
    <td background="image.jpg"></td>
  </tr>
</table>

My goal is to access the background attribute inside the td tag.


Solution

  • Use a foreach to make life more easier

    foreach ($dom->getElementsByTagName('td') as $tag) {
        if ($tag->getAttribute('background')) {
            echo $tag->getAttribute('background'); //"prints" image.jpg
        }
    }
    

    Working Demo