[使用DOMDocument :: saveHTML进行编辑时如何避免关闭HTML片段

问题描述 投票:2回答:1

我的目标是向divul容器添加自定义数据属性,如果该容器使用特定的类。我从包含有效HTML(包含其内容的完整div和结束</div>)或仅包含开头div(不包含其内容和结束</div>)的HTML片段开始。

这是我可能从以下内容开始的示例:

<div id='gallery-7222-1' class='gallery galleryid-7222 gallery-columns-3 gallery-size-thumbnail'>

这是到目前为止我尝试过的:

// grab all containers from the HTML.
$dom_doc = new DOMDocument();

/*
 * $html here can be the example I posted above.
 * LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD are used
 * to avoid adding a doctype and wrapping the whole output in HTML tags.
 */
$dom_doc->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );

// Let's look for lists and divs.
$ul_tags  = $dom_doc->getElementsByTagName( 'ul' );
$div_tags = $dom_doc->getElementsByTagName( 'div' );

/*
 * Loop through each ul, and add the data.
 * I do more things in there, like checking for what class the ul has,
 * but I've simplified things here. 
 */
foreach ( $ul_tags as $ul_tag ) {
    $ul_tag->setAttribute( 'data-foo', 'bar' );
}

/*
 * Loop through each div, and add the data.
 * I do more things in there, like checking for what class the div has,
 * but I've simplified things here. 
 */
foreach ( $div_tags as $div_tag ) {
    $div_tag->setAttribute( 'data-foo', 'bar' );    
}

// Save our updated HTML.
$html = $dom_doc->saveHTML();

返回的HTML包含新的data属性,但也包含我在这里并不需要的结尾</div>。在这里你可以看到它:https://ideone.com/sVfAOn

我首先想到只用</div>删除该结尾的substr,但我不能这样做:-在某些情况下,我的原始HTML实际上确实包含一个我想保留的div标记。-有时我可能正在编辑包含ul的字符串。

我将如何阻止saveHTML()在这里变得如此聪明,并试图为我修复HTML?

谢谢!

我的目标是将自定义数据属性添加到div和ul容器,如果该容器使用特定的类。我从包含有效HTML(包含其内容和...

php domdocument
1个回答
0
投票

[不,您不能说服HTML解析器不解析HTML。最好的解决方案是首先重新考虑如何获取数据的方法,并确保不获取碎片。

© www.soinside.com 2019 - 2024. All rights reserved.