为了账号安全,请及时绑定邮箱和手机立即绑定

php dom创建元素但自关闭

php dom创建元素但自关闭

PHP
Helenr 2021-06-30 14:51:53
我想创建一个 html 块,如下所示:<media>    <media-reference source='15.jpg' />    <media-caption>caption</media-caption>    <hasSyndicationRights>1</hasSyndicationRights>    <licenseId>1</licenseId>    <licensorName>name</licensorName></media>但是在我的代码中<media-reference>是这样关闭的</media-reference>。我怎样才能关闭那个标签?这是我的代码:$valFieldBody = '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio labore aut hic soluta! Animi quaerat unde commodi minus dicta, a quidem. Soluta quaerat delectus, id, dolor ex placeat molestiae quae.</p><p><img  height="500" src="15.jpg" width="500"/></p>';$htmlEncoded = mb_convert_encoding($valFieldBody, 'HTML-ENTITIES', 'UTF-8');$doc = new DOMDocument;$opcionesLibXML = LIBXML_COMPACT | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD;libxml_use_internal_errors(true);@$doc->loadHTML($htmlEncoded, $opcionesLibXML);libxml_use_internal_errors(false);$img_tag = $doc->getElementsByTagName('img');foreach ($img_tag as $key => $img_items){    $img_src = $img_items->getAttribute('src');    $tag_media = $doc->createElement('media');    $tag_media_reference = $doc->createElement('media-reference');    $tag_media_reference->setAttribute('mime-type','image/jpg');    $tag_media_reference->setAttribute('source',$img_src);    $tag_media_caption = $doc->createElement('media-caption',$img_title);    $tag_hasSyndicationRights = $doc->createElement('hasSyndicationRights','1');    $tag_licenseId = $doc->createElement('licenseId','1');    $tag_licensorName = $doc->createElement('licensorName',$img_title);    $tag_media->appendChild($tag_media_reference);    $tag_media->appendChild($tag_media_caption);    $tag_media->appendChild($tag_hasSyndicationRights);    $tag_media->appendChild($tag_licenseId);    $tag_media->appendChild($tag_licensorName);    $img_items->parentNode->replaceChild($tag_media, $img_items);}$valFieldBody = $doc->saveHTML($doc->documentElement);现在我str_replace用来改变它:$valFieldBody = str_replace("></media-reference>"," />", $valFieldBody);
查看完整描述

1 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

问题是saveHTML()使用它自己的规则创建输出(据我所知)并且并不总是根据 XHTML 标准编写内容。相反,如果你使用它写出来,saveXML()你应该得到一个更标准的输出


$valFieldBody = $doc->saveXML($doc->documentElement);

这使...


<p>

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio labore

    aut hic soluta! Animi quaerat unde commodi minus dicta, a quidem.

    Soluta quaerat delectus, id, dolor ex placeat molestiae quae.

    <p>

        <media>

            <media-reference mime-type="image/jpg"

                source="15.jpg" />

            <media-caption>abcd</media-caption>

            <hasSyndicationRights>1</hasSyndicationRights>

            <licenseId>1</licenseId>

            <licensorName>abcd</licensorName>

        </media>

    </p>

</p>

(请注意,如果您的原始来源不是 XHTML,则保存为 XML 实际上可能会导致其他问题)


查看完整回答
反对 回复 2021-07-02
  • 1 回答
  • 0 关注
  • 125 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信