title: PHP htmlentities() without converting html tags
body: <p>I've found a few posts which refer to the problem, but none of them fully resolve it.</p>
  
  <p>I need the function which will output the content converting all special characters in the way the htmlentities() would, but preserving all html tags.</p>
  
  <p>I've tried many different approaches, but as I've mentioned above - none of them works as expected.</p>
  
  <p>I was wondering whether there would be a way of doing it using PHP class DomDocument.</p>
  
  <p>I've tried to do it using the following:</p>
  
  <pre><code>$objDom = new DOMDocument('1.0', 'utf-8');
  $objDom-&gt;loadhtml($content);
  return $objDom-&gt;savehtml();
  </code></pre>
  
  <p>which works, but it also adds the entire structure of the page i.e. </p>
  
  <pre><code>&lt;head&gt;&lt;body&gt; etc.
  </code></pre>
  
  <p>I only need the content of the $content variable to be converted and job done.</p>
  
  <p>Another thing worth to mention here is that $content might also have some characters converted to xhtml complaint - as it comes from Wysiwyg. So it might containt &amp; etc., which should also be preserved.</p>
  
  <p>Anyone knows the way to do it with DomDocument - perhaps I should use different save method?</p>
  
  <p><strong>Ok - I've come up with the following - not great, but does the job spot on:</strong></p>
  
  <pre><code>$objDom = new DOMDocument('1.0', 'UTF-8');
  $objDom-&gt;loadHTML($string);
  $output = $objDom-&gt;saveXML($objDom-&gt;documentElement);
  $output = str_replace('&lt;html&gt;&lt;body&gt;', '', $output);
  $output = str_replace('&lt;/body&gt;&lt;/html&gt;', '', $output);
  $output = str_replace('&amp;#13;', '', $output);
  return $output; 
  </code></pre>
  
  <p>Any better ideas would be much appreciated.</p>