Reputation: 20223
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
Upvotes: 0
Views: 448
Reputation: 19482
The second argument of DOMXpath::query() has to be a context node, you can not just use some HTML string. I suggest using DOMXpath::evaluate() anyway. The syntax of both methods is the same, but query()
is limited to Xpath expressions that return a node list, evaluate()
allows Xpath expressions that return scalars, too.
$html = <<<HTML
<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>
HTML;
$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);
// for each td element
foreach ($xpath->evaluate('//td') as $cell) {
// for each img inside a p
foreach ($xpath->evaluate('.//p//img', $cell) as $img) {
var_dump($img->getAttribute('src'));
}
}
Output: https://eval.in/147576
string(28) "forMerrin_files/image020.png"
Upvotes: 1
Reputation: 24116
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)
Upvotes: 1