Teiv
Teiv

Reputation: 2635

Insert text after/before an self-closing tag using DOM in PHP?

$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?

Upvotes: 1

Views: 1166

Answers (1)

Marc B
Marc B

Reputation: 360602

Try:

$img->parentNode->insertBefore($before, $img);

Adding $img as 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.

   <span>  <-- parentNode
      <b>This is some text before the image</b>
      <img ...>   <--- $img node
      <i>This is some text after the image</b>
   </span>

Without the extra argument, you get:

  <span>
     <b>...</b>
     <img ...>
     <i>...</i>
     new text node here   <-- appended to parent Node's children, e.g. last
  </span>

WITH the argument, you get:

  <span>
     <b>...</b>
     new text node here   <--the "before" position
     <img ...>
     <i>...</i>
  </span>

Upvotes: 3

Related Questions