the_content() printing DOCTYPE, and tags in the middle of page

Ok so, this solution is very particular to my case but maybe it can help point somebody else in the right direction in the future if they encounter a similar problem.

I have a custom function that adds a CSS class for lazy-loading images into all <img> tags that are present in the_content().

In this function I am using the following code:

$document = new DOMDocument();
$document->loadHTML( utf8_decode( $content ) );

The DOCTYPE, html tags and body tags were appearing because of PHP’s loadHTML method.

Changing the above code to the following has solved this issue.

$document = new DOMDocument();
$document->loadHTML( utf8_decode( $content ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );

I found the details I needed to solve this problem here: https://stackoverflow.com/questions/4879946/how-to-savehtml-of-domdocument-without-html-wrapper