DOMXPath - 如何将元素包装在 HTML 标记中?

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

我想在 <p style="text-align:center"></p> 中扭曲 <img> 元素。 这是我目前的代码:

$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();

这是代码生成的结构:

最后我想要:

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

您需要做的是创建一个新的段落元素(具有新属性)并用这个新标签替换图像标签,然后将 img 标签添加回新的段落标签中...

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