title: Why Does DOM Change Encoding?
body: <pre><code>$string = file_get_contents('http://example.com');
  
  if ('UTF-8' === mb_detect_encoding($string)) {
      $dom = new DOMDocument();
      // hack to preserve UTF-8 characters
      $dom-&gt;loadHTML('&lt;?xml encoding="UTF-8"&gt;' . $string);
      $dom-&gt;preserveWhiteSpace = false;
      $dom-&gt;encoding = 'UTF-8';
      $body = $dom-&gt;getElementsByTagName('body');
      echo htmlspecialchars($body-&gt;item(0)-&gt;nodeValue);
  }
  </code></pre>
  
  <p>This changes all UTF-8 characters to Å, ¾, ¤ and other rubbish. Is there any other way how to preserve UTF-8 characters?</p>
  
  <p>Don't post answers telling me to make sure I am outputting it as UTF-8, I made sure I am.</p>
  
  <p>Thanks in advance :)</p>