title: Convert utf8 to latin1 in PHP. All characters above 255 convert to char references
body: <p>I need to convert text in UTF-8 into text encoded in ISO-8859-1 such that any character that are not part of ISO-8859-1 set would turn into character references. (ex <code>&amp;#946;</code>)</p>
  
  <p>Example: I want to turn text like</p>
  
  <pre><code>hello é β 水
  </code></pre>
  
  <p>into</p>
  
  <pre><code>hello é &amp;#946; &amp;#27700;
  </code></pre>
  
  <p>I am doing all this in PHP. I tried built-in functions, iconv, and tidy and combination of those and still cant get a reliable solution.</p>
  
  <p>Here is what I have so far</p>
  
  <pre><code>// convert any characters fount in the entity table into HTML entities
  // do not double encode entities, do not mess with quotes
  // use UTF-8 as character encoding because the page submits UTF-8
  $str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
  //print $str."\n";
  
  // convert text from UTF-8 to ISO-8859-1, 
  // characters that cannot be converted will be converted to ?
  $str = utf8_decode($str);
  //print $str."\n";    
  
  // make string XML valid.
  // mainly it converts text entities into numeric entities.
  $opts = array(  "output-xhtml"      =&gt; true, 
              "output-xml"        =&gt; true, 
              "show-body-only"    =&gt; true,
              "numeric-entities"  =&gt; true,
              "wrap"              =&gt; 0,
              "indent"            =&gt; false,
              "char-encoding" =&gt; 'latin1'
          );
  $tidy = tidy_parse_string($str, $opts,'latin1');
  tidy_clean_repair($tidy);
  $str = tidy_get_output($tidy);      
  //print $str."\n";
  </code></pre>