简体   繁体   中英

DOMXPath - How to wrap an element in a HTML tag?

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: 在此处输入图片说明

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>

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM