$imgs = $xpath->query('//img');
$i = 0;
foreach($imgs as $img) {
$before = new DOMText($captions[$i]);
$img->parentNode->insertBefore($before);
$i++;
}
I want to insert some texts before a tag however I can’t make this to work. The texts are sometimes inserted into wrong places. How can I solve this?
Try:
Adding
$imgas an argument (a ‘reference node’) to the insert function explicitly tells insert where in the hierarchy you want to insert the new node. Otherwise the docs simply say “appended to the children”, which means the new node will be the last one of the parent’s children.e.g.
Without the extra argument, you get:
WITH the argument, you get: