PHP DOM:
PHP , ; DOM, , .
(, , , JS)
$html = <<<HTML
<div id="content">
...
...buch of html or whateve
</div>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
for ($i = $divs->length - 1 ; $i > -1 ; $i--) {
$div = $divs->item($i);
if ($div->hasAttribute('id')) {
$id = $div->getAttribute('id');
$comment = $dom->createComment("End of {$id}");
if($div->nextSibling) {
$div->parentNode->insertBefore($comment, $div->nextSibling);
} else {
$div->parentNode->appendChild($comment);
}
}
}
echo $dom->saveHTML();
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div id="content">
...
...buch of html or whateve
</div>
</body></html>
:
- DOM allows you to load and parse invalid HTML
- And generates valid-HTML
And what it does:
- Download the HTMl string using
DOMDocument - Search all tags
<div> - Forerunner tag
<div>:- If he has attributes
id, - Get value
- Create a comment based on this value
- And add it to the DOM after the tag
</div>
Another solution, thinking about this, would probably be to use XPath instead of getElementsByTagName+ hasAttribute...
source
share