简体   繁体   English

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

[英]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> .我想在<p style="text-align:center"></p>扭曲<img>元素。 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...您需要做的是创建一个新的段落元素(具有新属性)并用这个新标签替换图像标签,然后将 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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