title: Looking for a PHP script that can clean up bad HTML
body: <p>I am in the process of writing a PHP command line script to convert hundreds of HTML snippets into Markdown using the <a href="http://milianw.de/projects/markdownify/" rel="noreferrer">Markdownify</a> library. However, I have come across a situation where some of my HTML is not structured well enough to be used with Markdownify. So I first need to send my HTML through some library that can clean it up and add optional closing tags, etc. I will be working with partial blocks of HTML, not complete HTML documents, so the HTML that is returned must be partial (and not include the doctype, etc).</p>
  <p>Do you know of a PHP script that can convert HTML to XHTML?</p>
  <h2>Solution:</h2>
  <p>Utilize the <a href="http://php.net/manual/en/domdocument.loadhtml.php" rel="noreferrer">PHP DOMDocument class</a>. It will format your HTML even if it is broken. Then you can extract the cleaned up HTML:</p>
  <pre><code>libxml_use_internal_errors(true); //use this to prevent warning messages from displaying because of the bad HTML
  
  $doc = new DOMDocument();
  $doc-&gt;loadHTML($badHtml);
  $goodHtml = $doc-&gt;saveHTML();
  </code></pre>
  <p>This will return a full HTML document (with the cleaned up version in the body tag), even though I passed it a partial block of HTML, so I can extract the cleaned up partial with this regex:</p>
  <pre><code>$goodHtmlPartial = trim(ereg_replace('(.*)&lt;body&gt;(.*)&lt;/body&gt;(.*)', '\2', $goodHtml));
  </code></pre>