Search code examples
phpxmldomdocumentgetelementsbytagname

Why the getElementsByTagName is not working in this example


I have an DomElement with this content:

$cell =  <td colspan=3>
             <p class=5tablebody>
                 <span style='position:relative;top:14.0pt'>
                     <img width=300 height=220 src="forMerrin_files/image020.png">
                 </span>
             </p>
         </td>

There, I am geting the p element with:

$paragraphs = $xpath->query('.//p', $cell); 

My goal is to get the img element from the cell element.

I have tried:

$paragraph->getElementsByTagName('img')->item(0);

But I am getting null. Any idea why?

Thank you


Solution

  • Is this what you after?

    $htmlStr = '<td colspan=3>
                 <p class=5tablebody>
                     <span style=\'position:relative;top:14.0pt\'>
                         <img width=300 height=220 src="forMerrin_files/image020.png">
                     </span>
                 </p>
             </td>';
    
    $doc = new DOMDocument();
    $doc->loadHTML($htmlStr);
    
    $paragraphs = $doc->getElementsByTagName('img');
    var_dump($paragraphs->item(0)->getAttribute('src'));
    

    Outputs:

    string 'forMerrin_files/image020.png' (length=28)