0

I want to warp an <img> element in a <p style="text-align:center"></p>. This is the code I have so far:

$dom_err = libxml_use_internal_errors(true);
$dom = new \DOMDocument('1.0', 'utf-8');
$dom->loadHtml(mb_convert_encoding($arr['nm_corpo_artigo'], 'HTML-ENTITIES', 'UTF-8'));
$xpath = new \DOMXPath($dom);
foreach ($xpath->query("//figure/img") as $img) {
    $img->setAttribute('style','max-width: 100%; height: auto;');
    $img->setAttribute('class','mb-4 mt-4');
}
$body = $dom->saveHTML();

And this is the structure genrated by the code: enter image description here

At the end Iwould like to have:

<figure ...>
   <p style="text-align:center"><img ...><figcaption>...</p>
</figure ...>

...

<?xml version="1.0" standalone="yes"?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
      <html>
        <body>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris elementum sagittis est in vestibulum. Maecenas vitae auctor nisi, id ullamcorper ex. Ut l ▶
          <p>Praesent et ante ac dolor sagittis ultricies ac ac ligula. Quisque iaculis lorem non est ornare, ornare varius justo aliquet. Vestibulum quam tortor, pos ▶
          <figure class="image">
            <img src="/storage/12/articles/pictures/body_1574716135628_045090d10819d1777ed93e4e1a1cf079.jpeg"/>
            <figcaption>ttttt</figcaption>
          </figure>
          <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean in urna nibh. Quisque fermentum lobortis euismod. Ut ▶
          <p>In pharetra efficitur sapien, a venenatis velit. Donec rutrum ut nunc nec mollis. Suspendisse ac auctor purus. Curabitur nec eleifend ipsum, eu aliquet t ▶
          <p>Vestibulum ullamcorper ante pharetra quam pharetra dictum. Fusce sed turpis eget lacus pretium sollicitudin malesuada sagittis nulla. Integer pulvinar or ▶
        </body>
      </html>
IgorAlves
  • 5,086
  • 10
  • 52
  • 83

1 Answers1

2

What you need to do is create a new paragraph element (with the new attribute) and replace the image tag with this new tag and then add the img tag back into the new paragraph tag...

foreach ($xpath->query("//figure/img") as $img) {
    $img->setAttribute('style','max-width: 100%; height: auto;');
    $img->setAttribute('class','mb-4 mt-4');
    $p = $dom->createElement("p");
    $p->setAttribute('style', 'text-align:center');
    $img->parentNode->replaceChild($p, $img);
    $p->appendChild($img);
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Hey @Nigel could you help me with this issue. It is almost the same you posted but for some reason I cant warpp in the browser. I can do that in the test.https://stackoverflow.com/questions/59056036/domxpath-not-expected-behaviour-as-in-the-test-object-is-not-being-wrapped-h . The point is I forgot to encapsulate the caption. It should be straighforward – IgorAlves Nov 26 '19 at 17:08