title: Fix HTML fragment
body: <p>I'm trying to learn how to use <a href="http://es.php.net/manual/en/book.dom.php" rel="nofollow">PHP's DOM functions</a>. As an exercise, I want to repair an invalid HTML <em>fragment</em>. So far, I've been able to produce a <em>full document</em>:</p>
  
  <pre><code>&lt;?php
  
  $fragment = '&lt;div style="font-weight: bold"&gt;Lorem ipsum &lt;div&gt;dolor sit amet,
      &lt;strong&gt;&lt;em class=foo&gt;luptate&lt;/strong&gt;&lt;/em&gt;. Excepteur proident,
      &lt;div class="bar"&gt;sunt in culpa&lt;/div&gt; officia est laborum.';
  
  $doc = new DOMDocument;
  libxml_use_internal_errors(TRUE);
  $doc-&gt;loadHTML($fragment);
  libxml_use_internal_errors(FALSE);
  $doc-&gt;formatOutput = TRUE;
  echo $doc-&gt;saveHTML();
  
  ?&gt;
  </code></pre>
  
  <p>... which prints:</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt;
  &lt;html&gt;&lt;body&gt;&lt;div style="font-weight: bold"&gt;Lorem ipsum &lt;div&gt;dolor sit amet,
      &lt;strong&gt;&lt;em class="foo"&gt;luptate&lt;/em&gt;&lt;/strong&gt;. Excepteur proident,
      &lt;div class="bar"&gt;sunt in culpa&lt;/div&gt; officia est laborum.&lt;/div&gt;
  &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>My questions:</p>
  
  <ol>
  <li>Is there a way to print only the HTML that corresponds to the original fragment?</li>
  <li>Is there a more appropriate built-in library for such task?</li>
  </ol>