utf8_decode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

utf8_decode --  将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。

描述

string utf8_decode ( string data )

该函数将用 UTF-8 编码的数据解码为 ISO-8859-1 编码。

请参阅 utf8_encode() 以查看关于 UTF-8 编码的解释。


add a note add a note User Contributed Notes
benny at vh-dr dot com
21-Mar-2006 06:48
2ge, thanks a heap! i was about to go crazy over this stuff...
just edited your function a little, to replace whitespaces with +, and changing and to a plain e.

function urlize($url) {
 $search = array('/[\\s]/','//', '//', '/--+/', '/^-+/', '/-+$/' );
 $replace = array( '+', 'e', 'e', '-', '', '');
 return preg_replace($search, $replace, utf2ascii($url));
}
2ge at NO2geSPAM dot us
26-Jan-2006 05:00
Hello all,

I like to use COOL (nice) URIs, example: http://server/fucking-amal
I'm using UTF8 as input, so I have to write a function UTF8toASCII to have nice URI. Here is what I come with:

<?php
function urlize($url) {
 
$search = array('/[^a-z0-9]/', '/--+/', '/^-+/', '/-+$/' );
 
$replace = array( '-', '-', '', '');
 return
preg_replace($search, $replace, utf2ascii($url));
}   

function
utf2ascii($string) {
 
$iso88591  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7";
 
$iso88591 .= "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
 
$iso88591 .= "\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF7";
 
$iso88591 .= "\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF";
 
$ascii = "aaaaaaaceeeeiiiidnooooooouuuuyyy";
 return
strtr(mb_strtolower(utf8_decode($string), 'ISO-8859-1'),$iso88591,$ascii);
}

echo
urlize("Fucking ml");

?>

I hope this helps someone.
peter dot mescalchin at geemail dot com
27-Dec-2005 01:43
Adding to below I have a few more MS word characters that need replacing. Found this was required when "fixing" some phpmyadmin export scripts from a live server where MS word characters were all through the content - before importing them back into my local mySQL database.

The code I wrote for this process also does a strpos for any extra "\\xe2\\x80" strings - which are the tell-tale sign of any funny characters I want removed.

Here are my updated arrays()

<?php
$badchr
= array(
  
"\\xe2\\x80\\xa6",        // ellipsis
  
"\\xe2\\x80\\x93",        // long dash
  
"\\xe2\\x80\\x94",        // long dash
  
"\\xe2\\x80\\x98",        // single quote opening
  
"\\xe2\\x80\\x99",        // single quote closing
  
"\\xe2\\x80\\x9c",        // double quote opening
  
"\\xe2\\x80\\x9d",        // double quote closing
  
"\\xe2\\x80\\xa2"        // dot used for bullet points
  
);

$goodchr = array(
  
'...',
  
'-',
  
'-',
  
'\\'',
   '''
,
  
'"',
  
'"',
  
'*'
  
);
?>
php-net at ---NOSPAM---lc dot yi dot org
08-Dec-2005 04:04
I've just created this code snippet to improve the user-customizable emails sent by one of my websites.

The goal was to use UTF-8 (Unicode) so that non-english users have all the Unicode benefits, BUT also make life seamless for English (or specifically, English MS-Outlook users).  The niggle: Outlook prior to 2003 (?)  does not properly detect unicode emails.  When "smart quotes" from MS Word were pasted into a rich text area and saved in Unicode, then sent by email to an Outlook user, more often than not, these characters were wrongly rendered as "greek".

So, the following code snippet replaces a few strategic characters into html entities which Outlook XP (and possibly earlier) will render as expected.  [Code based on bits of code from previous posts on this and the htmlenties page]
<?php
   $badwordchars
=array(
      
"\xe2\x80\x98", // left single quote
      
"\xe2\x80\x99", // right single quote
      
"\xe2\x80\x9c", // left double quote
      
"\xe2\x80\x9d", // right double quote
      
"\xe2\x80\x94", // em dash
      
"\xe2\x80\xa6" // elipses
  
);
  
$fixedwordchars=array(
      
"&#8216;",
      
"&#8217;",
      
'&#8220;',
      
'&#8221;',
      
'&mdash;',
      
'&#8230;'
  
);
  
$html=str_replace($badwordchars,$fixedwordchars,$html);
?>
yannikh at gmeil dot com
08-Dec-2005 03:34
I had to tackle a very interesting problem:

I wanted to replace all \xXX in a text by it's letters. Unfortunatelly XX were ASCII and not utf8. I solved my problem that way:
<?php preg_replace ('/\\\\x([0-9a-fA-F]{2})/e', "pack('H*',utf8_decode('\\1'))",$v); ?>
thierry.bo # netcourrier point com
02-Oct-2005 03:53
to complete my previous test, here is the summarize with :

- if ($string == utf8_decode($string))
- if ($string == iconv('UTF-8', 'UTF-8', $string)

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding
203 lines are valid  UTF 8 strings using using utf8_decode
224 lines are valid  UTF 8strings using using iconv

If we trust the file used for this test, no need to use a regexp, use XML::utf8_decode() to test your strings, you get the same detection chance as the three regexp tested, and XML Parser extension is almost always available, unlike Iconv and Multibyte String functions.
thierry.bo # netcourrier point com
01-Oct-2005 03:38
In response to fhoech (22-Sep-2005 11:55), I just tried a simultaneous test with the file UTF-8-test.txt using your regexp, 'j dot dittmer' (20-Sep-2005 06:30) regexp (message #56962), `php-note-2005` (17-Feb-2005 08:57) regexp in his message on `mb-detect-encoding` page (http://us3.php.net/manual/en/function.mb-detect-encoding.php#50087) who is using a regexp from the W3C (http://w3.org/International/questions/qa-forms-utf-8.html), and PHP mb_detect_encoding function.

Here are a summarize of the results :

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding

Here are the lines with differences (left to right, phpnote, j.dittmer and fhoech) :

Line #70 : NOT UTF8|IS UTF8!|IS UTF8! :2.1.1 1 byte (U-00000000): ""
Line #79 : NOT UTF8|IS UTF8!|IS UTF8! :2.2.1 1 byte (U-0000007F): ""
Line #81 : IS UTF8!|IS UTF8!|NOT UTF8 :2.2.3 3 bytes (U-0000FFFF): "&#65535;" |
Line #267 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.1 U+FFFE = ef bf be = "&#65534;" |
Line #268 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.2 U+FFFF = ef bf bf = "&#65535;" |

Interesting is that you said that your regexp corrected j.dittmer regexp that failed on 5.3 section, but it my test I have the opposite result ?!

I ran this test on windows XP with PHP 4.3.11dev. Maybe these differences come from operating system, or PHP version.

For mb_detect_encoding I used the command :

mb_detect_encoding($line, 'UTF-8, ISO-8859-1, ASCII');
fhoech
23-Sep-2005 01:55
Sorry, I had a typo in my last comment. Corrected regexp:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbd]|
\\xee[\\x80-\\xbf]{2}|
\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$
fhoech
23-Sep-2005 01:12
JF Sebastian's regex is almost perfect as far as I'm concerned. I found one error (it failed section 5.3 "Other illegal code positions" from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) which I corrected as follows:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbc]|
\\xee[\\x80-\\xbf]{2}|
\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$

(Again, concatenate to one single line to make it work)
j dot dittmer at portrix dot net
20-Sep-2005 08:30
The regex in the last comment has some typos. This is a
syntactically valid one, don't know if it's correct though.
You've to concat the expression in one long line.

^(
[\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}
)*$
chris at mrwsp dot com
09-Aug-2005 06:54
A small improvement.

JF Sebastian's regex for UTF-8 is not quite correct.  Because code points could otherwise be coded in more than one way using UTF-8, the Standard stipulates that the shortest possible representation for a character should be used.  So some 'duplicate' combinations his regex accepts are not valid UTF-8.  Additionally, his regex accepts characters beyond the valid Unicode code space.

The regex should be:

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}*$)
miracle at balkansys dot com
14-Jun-2005 05:24
The best multilanguage library I have found is a part of a CMS system - typo3

http://www.typo3.org

It can convert from and to any charset + it does it by three methods - mbstring, iconv, or the raw way by scripts. It uses only one of these techniques - the fastest if available.

That was the only way I could make mysql 3.23 contain letters in almost any language, while maintaining my website in utf-8 only.
Denjs
11-May-2005 09:09
i had some problems whith encode-decode russian-cp1251 strings into utf8, like browser do "this" in url...
(my Apache runs under windows and some local files have russian names - it needs to create correct url to them)

problem resolves whith utf8-class created by Alexandar Minkovsky.

download here:
http://www.phpclasses.org/browse/package/1974.html

UTF8 class can convert text between UTF-8 and other encodings. puplished under "BSD License"
Vladimir Stwora, vlad4321 at fastmail dot fm
09-May-2005 06:41
If you want to convert utf-8 to ascii, you can use the following procedure:

<?php
function utf2ascii($string) {
  
$string=iconv('utf-8','windows-1250',$string);
  
$win  ='...'// I was unable to paste here all set of characters, but you get the point
  
$ascii='zyaieuu...';
  
$string = StrTr($string,$win,$ascii);
   return
$string;
  }
?>
This works based on the assumption that you know what language text (and thus what charset) you want to convert from. In the above example I am converting from an eastern European language, so I know I can safely use windows-1250 charset as an intermediem charset. You will have to adjust the charset based on your language.

Please remember that you have to save this file separately and it must be coded in the charset, which you will call within function iconv. Otherwise it will not work.
JF Sebastian
30-Mar-2005 11:09
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
   return (preg_match('/[insert regular expression here]/', $string) === 1);
}
ivanmaz(remove) at mech dot math dot msu dot su
16-Mar-2005 07:50
Here is my variant of UTF8 to Cyrillic Win-1251 encoding convertor that replaces all characters but latin and Russian ones with &#...; entities:

function utf2win1251 ($s)
{
 $out = "";

 for ($i=0; $i<strlen($s); $i++)
 {
  $c1 = substr ($s, $i, 1);
  $byte1 = ord ($c1);
  if ($byte1>>5 == 6) // 110x xxxx, 110 prefix for 2 bytes unicode
  {
   $i++;
   $c2 = substr ($s, $i, 1);
   $byte2 = ord ($c2);
   $byte1 &= 31; // remove the 3 bit two bytes prefix
   $byte2 &= 63; // remove the 2 bit trailing byte prefix
   $byte2 |= (($byte1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
   $byte1 >>= 2; // c1 shifts 2 to the right

   $word = ($byte1<<8) + $byte2;
   if ($word==1025) $out .= chr(168);                    //
   elseif ($word==1105) $out .= chr(184);                //
   elseif ($word>=0x0410 && $word<=0x044F) $out .= chr($word-848); // - -
   else
   { 
     $a = dechex($byte1);
     $a = str_pad($a, 2, "0", STR_PAD_LEFT);
     $b = dechex($byte2);
     $b = str_pad($b, 2, "0", STR_PAD_LEFT);
     $out .= "&#x".$a.$b.";";
   }
  }
  else
  {
   $out .= $c1;
  }
 }

 return $out;
}

The function is based on 2 other functions posted below.
I hope it will help those who convert UTF8-encoded text to Win-1251 to use it safely on Russian web pages (works fine in all browsers).
marcelo at maccoy dot com dot br
15-Feb-2005 02:24
function decode_utf8($str){
       # erase null signs in string
         $str=eregi_replace("^.{10,13}q\?","",$str);
       # paterns
           $pat = "/=([0-9A-F]{2})/";
           $cha="'.chr(hexdec(";
       # to decode with eval and replace
         eval("\$str='".
                 preg_replace($pat,$cha."'$1')).'",$str).
                 "';");
       # return
           return $str;
       }

Note:
It's possible put it in 3 lines, but I don't got in this first code submition.
husamb at maksimum dot net
27-Jan-2005 05:16
Hi, I collected the some scripts in this page and I written a new customizable script. You can switch easily iso type to convert. There are definitions in unicode.org page at http://www.unicode.org/Public/MAPPINGS/ISO8859/.

<?php
# GLOBAL VARIABLES
$url = "http://www.unicode.org/Public/MAPPINGS/ISO8859/8859-9.TXT";
//$url = "8859-9.txt";
$iso2utf = array();
$utf2iso = array();

# UNICODE MAPPING TABLE PARSING
function create_map($url){
   global
$iso2utf, $utf2iso;
  
$fl = @(file($url)) OR (die("cannot open file : $url\n"));
   for (
$i=0; $i<count($fl); $i++){
       if(
$fl[$i][0] != '#' && trim($fl[$i])){
           list(
$iso, $uni, $s, $desc) = split("\t",$fl[$i]);
          
$iso2utf[$iso] = $uni;
          
$utf2iso[$uni] = $iso;
       }
   }
}

# FINDING UNICODE LETTER'S DECIMAL ASCII VALUE
function uniord($c){
  
$ud = 0;
   if (
ord($c{0})>=0 && ord($c{0})<=127$ud = $c{0};
   if (
ord($c{0})>=192 && ord($c{0})<=223) $ud = (ord($c{0})-192)*64 + (ord($c{1})-128);
   if (
ord($c{0})>=224 && ord($c{0})<=239) $ud = (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
   if (
ord($c{0})>=240 && ord($c{0})<=247) $ud = (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
   if (
ord($c{0})>=248 && ord($c{0})<=251) $ud = (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
   if (
ord($c{0})>=252 && ord($c{0})<=253) $ud = (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
   if (
ord($c{0})>=254 && ord($c{0})<=255) $ud = false; //error
  
return $ud;
}

# PARSING UNICODE STRING
function utf2iso($source) {
   global
$utf2iso;
  
$pos = 0;
  
$len = strlen ($source);
  
$encodedString = '';
  
   while (
$pos < $len) {
      
$is_ascii = false;
      
$asciiPos = ord (substr ($source, $pos, 1));
       if((
$asciiPos >= 240) && ($asciiPos <= 255)) {
          
// 4 chars representing one unicode character
          
$thisLetter = substr ($source, $pos, 4);
          
$thisLetterOrd = uniord($thisLetter);
          
$pos += 4;
       }
       else if((
$asciiPos >= 224) && ($asciiPos <= 239)) {
          
// 3 chars representing one unicode character
          
$thisLetter = substr ($source, $pos, 3);
          
$thisLetterOrd = uniord($thisLetter);
          
$pos += 3;
       }
       else if((
$asciiPos >= 192) && ($asciiPos <= 223)) {
          
// 2 chars representing one unicode character
          
$thisLetter = substr ($source, $pos, 2);
          
$thisLetterOrd = uniord($thisLetter);
          
$pos += 2;
       }
       else{
          
// 1 char (lower ascii)
          
$thisLetter = substr ($source, $pos, 1);
          
$thisLetterOrd = uniord($thisLetter);
          
$pos += 1;
          
$encodedString .= $thisLetterOrd;
          
$is_ascii = true;
       }
       if(!
$is_ascii){
          
$hex = sprintf("%X", $thisLetterOrd);
           if(
strlen($hex)<4) for($t=strlen($hex);$t<4;$t++)$hex = "0".$hex;
          
$hex = "0x".$hex;
          
$hex = $utf2iso[$hex];
          
$hex = str_replace('0x','',$hex);
          
$dec = hexdec($hex);
          
$encodedString .= sprintf("%c", $dec);
       }
   }
   return
$encodedString;
}

# CREATING ISO2UTF & UTF2ISO MAPS
create_map($url);

# TESTING
$unicode_string = "Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3\xbcnyas\xc4\xb1";

echo
"unicode string : <b>" . $unicode_string . "</b>";
echo
"<br><br>";
echo
"ISO8859 (latin5 / turkish) converted string : <b>" . utf2iso($unicode_string) . "</b>";
?>

The unicode string is turkish. ITs mean in english is 'Economy and Business World' :)

Husam
rasmus at flajm dot se
19-Jan-2005 06:57
If you don't have the multibyte extension installed, here's a function to decode UTF-16 encoded strings. It support both BOM-less and BOM'ed strings, (big- and little-endian byte order.)

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 *
 * @param  string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode( $str ) {
   if(
strlen($str) < 2 ) return $str;
  
$bom_be = true;
  
$c0 = ord($str{0});
  
$c1 = ord($str{1});
   if(
$c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
   elseif(
$c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
  
$len = strlen($str);
  
$newstr = '';
   for(
$i=0;$i<$len;$i+=2) {
       if(
$bom_be ) { $val = ord($str{$i})  << 4; $val += ord($str{$i+1}); }
       else {       
$val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
      
$newstr .= ($val == 0x228) ? "\n" : chr($val);
   }
   return
$newstr;
}
?>
dobersch at gmx dot net
04-Nov-2004 10:11
Sorry, there's an error in my previous comment, my error_reporting was not set to E_ALL ... so the notices disappeared...

It seems that those Google URLs are not only UTF-8 encoded, but after encoding, several values also get replaced. (cp1252 ?)

Just the way as described in following comments on the utf8_encode() page:
http://de3.php.net/manual/de/function.utf8-encode.php#44843 and
http://de3.php.net/manual/de/function.utf8-encode.php#45226

Below I post a solution for getting back the ISO-8859-1 encoded string from the encoded data, by turning the function from Aidan the other way around.

hope this time, everything is alright...

<?PHP
ini_set
('error_reporting', E_ALL);
// map taken from http://de3.php.net/manual/de/function.utf8-encode.php#45226
$cp1252_map = array(
  
"\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
  
"\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
  
"\xc2\x83" => "\xc6\x92",    /* LATIN SMALL LETTER F WITH HOOK */
  
"\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
  
"\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
  
"\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
  
"\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
  
"\xc2\x88" => "\xcb\x86",    /* MODIFIER LETTER CIRCUMFLEX ACCENT */
  
"\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
  
"\xc2\x8a" => "\xc5\xa0",    /* LATIN CAPITAL LETTER S WITH CARON */
  
"\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
  
"\xc2\x8c" => "\xc5\x92",    /* LATIN CAPITAL LIGATURE OE */
  
"\xc2\x8e" => "\xc5\xbd",    /* LATIN CAPITAL LETTER Z WITH CARON */
  
"\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
  
"\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
  
"\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
  
"\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
  
"\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
  
"\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
  
"\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

  
"\xc2\x98" => "\xcb\x9c",    /* SMALL TILDE */
  
"\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
  
"\xc2\x9a" => "\xc5\xa1",    /* LATIN SMALL LETTER S WITH CARON */
  
"\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
  
"\xc2\x9c" => "\xc5\x93",    /* LATIN SMALL LIGATURE OE */
  
"\xc2\x9e" => "\xc5\xbe",    /* LATIN SMALL LETTER Z WITH CARON */
  
"\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

// I find this name a little misleading because the result won't be valid UTF8 data
function cp1252_to_utf8($str) {
   global
$cp1252_map;
   return 
strtr(utf8_encode($str), $cp1252_map);
}

function
cp1252_utf8_to_iso($str) { // the other way around...
 
global $cp1252_map;
  return 
utf8_decode( strtr($str, array_flip($cp1252_map)) );
}

$euro = "\xe2\x82\xac"// "google encoded" euro sign
$str = cp1252_utf8_to_iso($euro);

for(
$i=0; $i<strlen($str); $i++) {
  print
'&quot;' . $str[$i] . '&quot; - ' . ord($str[$i]) . ' (decimal)<br />';
}
?>
vpribish at shopping dot com
11-Sep-2004 02:55
big thanks to wielspm and mittag for the function to convert wide utf to html.  I have altered your function to output decimal html entities which i hear are more widely supported.  Also I've optimized it, it is now twice as fast.

<?php
function utf2html ($str) {
$ret = "";
$max = strlen($str);
$last = 0// keeps the index of the last regular character
for ($i=0; $i<$max; $i++) {
 
$c = $str{$i};
 
$c1 = ord($c);
 if (
$c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
  
$ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
  
$c1 &= 31; // remove the 3 bit two bytes prefix
  
$c2 = ord($str{++$i}); // the next byte
  
$c2 &= 63// remove the 2 bit trailing byte prefix
  
$c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
  
$c1 >>= 2; // c1 shifts 2 to the right
  
$ret .= "&#" . ($c1 * 100 + $c2) . ";"; // this is the fastest string concatenation
  
$last = $i+1;       
 }
}
return
$ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
Aidan Kehoe <php-manual at parhasard dot net>
31-Jan-2004 09:35
The fastest way I've found to check if something is valid UTF-8 is
<?php
if (iconv('UTF-8', 'UTF-8', $input) != $input) {
      
/* It's not UTF-8--for me, it's probably CP1252, the Windows
           version of Latin 1, with directed quotation marks and
           the Euro sign.  */
}
 
?>.
The iconv() C library fails if it's told a string is UTF-8 and it isn't; the PHP one doesn't, it just returns the conversion up to the point of failure, so you have to compare the result to the input to find out if the conversion succeeded.
lg83news at free dot fr
29-Dec-2003 01:40
Here are some functions for converting UTF-8 to and from Latin 9 (aka ISO-8859-15), if your PHP file is encoded as UTF-8.

<?php
function latin9_to_utf8($latin9str) { // replaces utf8_encode()
  
$trans = array(""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"");
  
$wrong_utf8str = utf8_encode($latin9str);
  
$utf8str = strtr($wrong_utf8str, $trans);
   return
$utf8str;
}
function
utf8_to_latin9($utf8str) { // replaces utf8_decode()
  
$trans = array(""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"");
  
$wrong_utf8str = strtr($utf8str, $trans);
  
$latin9str = utf8_decode($wrong_utf8str);
   return
$latin9str;
}
?>

Note: the above functions will not work if your PHP file is not encoded in UTF-8.

You can copy this binary data to your PHP file instead, it'll work with any encoding (including UTF-8) as long as you copy it as bytes, not characters:

<?php
function latin9_to_utf8($latin9str) { // replaces utf8_encode()
  
$trans = array(""=>"", ""=>" ", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"");
  
$wrong_utf8str = utf8_encode($latin9str);
  
$utf8str = strtr($wrong_utf8str, $trans);
   return
$utf8str;
}
function
utf8_to_latin9($utf8str) { // replaces utf8_decode()
  
$trans = array(""=>"", " "=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"", ""=>"");
  
$wrong_utf8str = strtr($utf8str, $trans);
  
$latin9str = utf8_decode($wrong_utf8str);
   return
$latin9str;
}
?>

(Note: the PHP manual is served as ISO-8859-1, but many of the bytes used here have no meaning in ISO-8859-1, so they'll probably be displayed as Windows-1252 if your using Windows, or garbage otherwise. Just copy the bytes!)
gto at interia dot pl
25-Nov-2003 11:12
Correction to function converting utf82iso88592 and iso88592tutf8.
Janusz forgot about "&#324;", and "&#380;" exchanged from "&#378;" here and there.

GTo

function utf82iso88592($tekscik) {
     $tekscik = str_replace("\xC4\x85", "&#261;", $tekscik);
     $tekscik = str_replace("\xC4\x84", '&#260;', $tekscik);
     $tekscik = str_replace("\xC4\x87", '&#263;', $tekscik);
     $tekscik = str_replace("\xC4\x86", '&#262;', $tekscik);
     $tekscik = str_replace("\xC4\x99", '&#281;', $tekscik);
     $tekscik = str_replace("\xC4\x98", '&#280;', $tekscik);
     $tekscik = str_replace("\xC5\x82", '&#322;', $tekscik);
     $tekscik = str_replace("\xC5\x81", '&#321;', $tekscik);
     $tekscik = str_replace("\xC5\x84", '&#324;', $tekscik);   
     $tekscik = str_replace("\xC5\x83", '&#323;', $tekscik);
     $tekscik = str_replace("\xC3\xB3", '', $tekscik);
     $tekscik = str_replace("\xC3\x93", '', $tekscik);
     $tekscik = str_replace("\xC5\x9B", '&#347;', $tekscik);
     $tekscik = str_replace("\xC5\x9A", '&#346;', $tekscik);
     $tekscik = str_replace("\xC5\xBC", '&#380;', $tekscik);
     $tekscik = str_replace("\xC5\xBB", '&#379;', $tekscik);
     $tekscik = str_replace("\xC5\xBA", '&#378;', $tekscik);
     $tekscik = str_replace("\xC5\xB9", '&#377;', $tekscik);
     return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
     $tekscik = str_replace("&#261;", "\xC4\x85", $tekscik);
     $tekscik = str_replace('&#260;', "\xC4\x84", $tekscik);
     $tekscik = str_replace('&#263;', "\xC4\x87", $tekscik);
     $tekscik = str_replace('&#262;', "\xC4\x86", $tekscik);
     $tekscik = str_replace('&#281;', "\xC4\x99", $tekscik);
     $tekscik = str_replace('&#280;', "\xC4\x98", $tekscik);
     $tekscik = str_replace('&#322;', "\xC5\x82", $tekscik);
     $tekscik = str_replace('&#321;', "\xC5\x81", $tekscik);
     $tekscik = str_replace('&#324;', "\xC5\x84", $tekscik);
     $tekscik = str_replace('&#323;',"\xC5\x83", $tekscik);
     $tekscik = str_replace('', "\xC3\xB3", $tekscik);
     $tekscik = str_replace('', "\xC3\x93", $tekscik);
     $tekscik = str_replace('&#347;', "\xC5\x9B", $tekscik);
     $tekscik = str_replace('&#346;', "\xC5\x9A", $tekscik);
     $tekscik = str_replace('&#380;', "\xC5\xBC", $tekscik);
     $tekscik = str_replace('&#379;', "\xC5\xBB", $tekscik);
     $tekscik = str_replace('&#378;', "\xC5\xBA", $tekscik);
     $tekscik = str_replace('&#377;', "\xC5\xB9", $tekscik);   
     return $tekscik;
} // iso885922utf8
nospam at jra dot nu
23-Nov-2003 07:48
There is an error in the 'smart_utf8_decode' function posted by ' goran_johansson' below. It should look like this:

function smart_utf8_decode($in_str)
{
   // Replace ? with a unique string
   $new_str = str_replace("?", "q0u0e0s0t0i0o0n", $in_str);

   // Try the utf8_decode
   $new_str=utf8_decode($new_str);

   // if it contains ? marks
   if (strpos($new_str,"?") !== false)
   {
       // Something went wrong, set new_str to the original string.
       $new_str=$in_str;
   }
   else
   {
       // If not then all is well, put the ?-marks back where is belongs
       $new_str = str_replace("q0u0e0s0t0i0o0n", "?", $new_str);
   }

   return $new_str;
}
janusz dot s at remove_this dot and_this dot poczta dot fm
25-Oct-2003 11:54
Here are functions to PROPERLY de/encode Unicode (UTF-8) string to/from ISO-8859-2 (Polish character set).

Regards,
Janusz

function utf82iso88592($tekscik) {
 $tekscik = str_replace("\xC4\x85", "", $tekscik);
 $tekscik = str_replace("\xC4\x84", '', $tekscik);
 $tekscik = str_replace("\xC4\x87", '', $tekscik);
 $tekscik = str_replace("\xC4\x86", '', $tekscik);
 $tekscik = str_replace("\xC4\x99", '', $tekscik);
 $tekscik = str_replace("\xC4\x98", '', $tekscik);
 $tekscik = str_replace("\xC5\x82", '', $tekscik);
 $tekscik = str_replace("\xC5\x81", '', $tekscik);
 $tekscik = str_replace("\xC3\xB3", '', $tekscik);
 $tekscik = str_replace("\xC3\x93", '', $tekscik);
 $tekscik = str_replace("\xC5\x9B", '', $tekscik);
 $tekscik = str_replace("\xC5\x9A", '', $tekscik);
 $tekscik = str_replace("\xC5\xBC", '', $tekscik);
 $tekscik = str_replace("\xC5\xBB", '', $tekscik);
 $tekscik = str_replace("\xC5\xBA", '', $tekscik);
 $tekscik = str_replace("\xC5\xB9", '', $tekscik);
 return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
 $tekscik = str_replace("", "\xC4\x85", $tekscik);
 $tekscik = str_replace('', "\xC4\x84", $tekscik);
 $tekscik = str_replace('', "\xC4\x87", $tekscik);
 $tekscik = str_replace('', "\xC4\x86", $tekscik);
 $tekscik = str_replace('', "\xC4\x99", $tekscik);
 $tekscik = str_replace('', "\xC4\x98", $tekscik);
 $tekscik = str_replace('', "\xC5\x82", $tekscik);
 $tekscik = str_replace('', "\xC5\x81", $tekscik);
 $tekscik = str_replace('', "\xC3\xB3", $tekscik);
 $tekscik = str_replace('', "\xC3\x93", $tekscik);
 $tekscik = str_replace('', "\xC5\x9B", $tekscik);
 $tekscik = str_replace('', "\xC5\x9A", $tekscik);
 $tekscik = str_replace('', "\xC5\xBC", $tekscik);
 $tekscik = str_replace('', "\xC5\xBB", $tekscik);
 $tekscik = str_replace('', "\xC5\xBA", $tekscik);
 $tekscik = str_replace('', "\xC5\xB9", $tekscik);
 return $tekscik;
} // iso885922utf8
bn2 (bn2 at ukr dot net)
01-Sep-2003 11:56
Function to decode uft8 to win-1251 (russian) charset. Don't support ukrainian letters. Support only 2-byte coding.

function utf8win1251($s){
$out="";$c1="";$byte2=false;
for ($c=0;$c<strlen($s);$c++){
$i=ord($s[$c]);
if ($i<=127) $out.=$s[$c];
if ($byte2){
$new_c2=($c1&3)*64+($i&63);
$new_c1=($c1>>2)&5;
$new_i=$new_c1*256+$new_c2;
if ($new_i==1025) $out_i=168; else
if ($new_i==1105) $out_i=184; else $out_i=$new_i-848;
$out.=chr($out_i);
$byte2=false;}
if (($i>>5)==6) {$c1=$i;$byte2=true;}
}
return $out;}
morris_hirsch at hotmail dot com
19-Aug-2003 12:43
Be aware that utf8_decode can not properly store ''wide'' code entities which have a numeric value too big for a byte.

This function may help you.  It converts utf8 to strict ASCII with no high-bit codes, they are all written as numerics.

// UTF-8 encoding
// bytes bits representation
// 1  7  0bbbbbbb
// 2  11  110bbbbb 10bbbbbb
// 3  16  1110bbbb 10bbbbbb 10bbbbbb
// 4  21  11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
// Each b represents a bit that can be used to store character data.

// input CANNOT have single byte upper half extended ascii codes

function numeric_entify_utf8 ($utf8_string) {

  $out = "";
  $ns = strlen ($utf8_string);
  for ($nn = 0; $nn < $ns; $nn++) {
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);

//1 7 0bbbbbbb (127)

   if ($ii < 128) $out .= $ch;

//2 11 110bbbbb 10bbbbbb (2047)

   else if ($ii >>5 == 6) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b2 = ($ii & 63);

  $ii = ($b1 * 64) + $b2;

     $ent = sprintf ("&#%d;", $ii);
     $out .= $ent;
   }

//3 16 1110bbbb 10bbbbbb 10bbbbbb

   else if ($ii >>4 == 14) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b2 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b3 = ($ii & 63);

  $ii = ((($b1 * 64) + $b2) * 64) + $b3;

     $ent = sprintf ("&#%d;", $ii);
     $out .= $ent;
   }

//4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb

   else if ($ii >>3 == 30) {
  $b1 = ($ii & 31);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b2 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b3 = ($ii & 63);

  $nn++;
   $ch = $utf8_string [$nn];
   $ii = ord ($ch);
  $b4 = ($ii & 63);

  $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;

     $ent = sprintf ("&#%d;", $ii);
     $out .= $ent;
   }

  }
  return $out;
}
johan dot andersson at strateg dot se
05-May-2003 04:25
A simple way to convert utf-8 encoded strings...
(PHP 4 >= 4.3.0)

<?php
$newstring
= html_entity_decode(htmlentities($utf8_string, ENT_COMPAT, 'UTF-8'));
?>

(For 4.1.0 >= PHP < 4.3.0 use this function instead of html_entity_decode)

<?php
function unhtmlentities ($string)
{
  
$trans_tbl = get_html_translation_table (HTML_ENTITIES);
  
$trans_tbl = array_flip ($trans_tbl);
   return
strtr ($string, $trans_tbl);
}

$newstring = unhtmlentities(htmlentities($utf8_string, ENT_COMPAT, 'UTF-8'));
?>

//Johan
24-Feb-2003 10:10
Oups, this is the non bugged version :)

Well sometimes you need to store a utf-8 string in a database table column with a fixed size.
Here is a function that fix a string which has been broken (by a substr for example) in a middle of a utf-8 char sequence.

function FixUtf8BrokenString($Desc)
{
 // UTF-8 encoding
 // bytes : representation
 // 1    : 0bbbbbbb
 // 2    : 110bbbbb 10bbbbbb
 // 3    : 1110bbbb 10bbbbbb 10bbbbbb
 // 4    : 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
 // to see if a string is broken in middle of a utf8 char
 // we search for last byte encoding size of utf-8 char
 // if number of last bytes in string is lower than encoding size
 // we remove those last bytes

 // if last byte is ord < 128, ok. we return !
 if (ord($Desc[strlen($Desc) - 1]) < (0x80))
   return $Desc

 // loop for finding byte encoding size
 $nbbytes = 1;
 while (ord($Desc[strlen($Desc) - $nbbytes]) > 0x7F)
 {
   if (ord($Desc[strlen($Desc) - $nbbytes]) > 0xBF)
     break;
   $nbbytes++;
 }

  // check if byte encoding size is encoding a size of 4 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xF0) && ($nbbytes == 4))
   return $Desc;
  // check if byte encoding size is encoding a size of 3 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xE0) && ($nbbytes == 3))
   return $Desc;
  // check if byte encoding size is encoding a size of 2 bytes
  if ((ord($Desc[strlen($Desc) - $nbbytes]) > 0xC0) && ($nbbytes == 2))
   return $Desc;
  // then this is the case where string is badly broken, we remove last bytes
  return substr($Desc, 0, -$nbbytes);
}

$str = "Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3\xbcnyas\xc4\xb1";
$broken = substr($str, 0, 12);
$fixed = FixUtf8BrokenString($broken);

echo "$str<hr>$fixed<hr>$broken<hr>";

Sebastien Meudec.
19-Dec-2002 01:08
addition to above entrie:

it does not mean "when it comes to a '='" but when it comes to a "0"
mittag - -add- -marcmittag- -dot- -de
19-Dec-2002 12:56
The above function does not work entirely correct. It comes to problems, if there is a leading "=" in one of the two Strings it produces and glues out of the two bytes of the unicode letter.

The following works:

<?php
//Convert Unicode to ASCII + Entities
$fp = fopen($DOCUMENT_ROOT."/your_unicode_text.txt", "r");
while ( !
feof($fp) )
{
$string = fgets($fp, 1000);

 
$utf2html_string .= $string;
}
$string2 = $utf2html_string;
fclose ( $fp);

function
utf2html ()
{
global
$utf2html_string;

$utf2html_retstr = "";
 for (
$utf2html_p=0; $utf2html_p<strlen($utf2html_string); $utf2html_p++) {
 
$utf2html_c = substr ($utf2html_string, $utf2html_p, 1);
 
$utf2html_c1 = ord ($utf2html_c);
  if (
$utf2html_c1>>5 == 6) {// 110x xxxx, 110 prefix for 2 bytes unicode
  
$utf2html_p++;
  
$utf2html_t = substr ($utf2html_string, $utf2html_p, 1);
 
$utf2html_c2 = ord ($utf2html_t);
  
$utf2html_c1 &= 31; // remove the 3 bit two bytes prefix
  
$utf2html_c2 &= 63; // remove the 2 bit trailing byte prefix
  
$utf2html_c2 |= (($utf2html_c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
  
$utf2html_c1 >>= 2; // c1 shifts 2 to the right
  
$a = dechex($utf2html_c1);
  
$a = str_pad($a, 2, "0", STR_PAD_LEFT);
  
$b = dechex($utf2html_c2);
  
$b = str_pad($b, 2, "0", STR_PAD_LEFT);

  
$utf2html_n_neu = $a.$b;
  
$utf2html_n_neu_speicher = $utf2html_n_neu;
  
$utf2html_n_neu = "&#x".$utf2html_n_neu.";";

    
 
$utf2html_retstr .= $utf2html_n_neu;
 
  }
  else {
  
$utf2html_retstr .= $utf2html_c;
  }
 }
 echo
$utf2html_retstr;
 
//return $utf2html_retstr;

}

utf2html();

?>
wielspm at xs4all dot nl
06-Dec-2002 01:44
Here is a function I made to convert all 2 byte utf in a &#xxx; form:

function utf2html ($utf2html_string)
{
  $utf2html_retstr = "";
  for ($utf2html_p=0; $utf2html_p<strlen($utf2html_string); $utf2html_p++):
   $utf2html_c = substr ($utf2html_string, $utf2html_p, 1);
   $utf2html_c1 = ord ($utf2html_c);
   if ($utf2html_c1>>5 == 6): // 110x xxxx, 110 prefix for 2 bytes unicode
     $utf2html_p++;
       $utf2html_t = substr ($utf2html_string, $utf2html_p, 1);
     $utf2html_c2 = ord ($utf2html_t);
     $utf2html_c1 &= 31; // remove the 3 bit two bytes prefix
     $utf2html_c2 &= 63; // remove the 2 bit trailing byte prefix
     $utf2html_c2 |= (($utf2html_c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
     $utf2html_c1 >>= 2; // c1 shifts 2 to the right
       $utf2html_n = dechex($utf2html_c1).dechex($utf2html_c2);
     $utf2html_retstr .= sprintf ("&#%03d;", hexdec($utf2html_n));
   else:
     $utf2html_retstr .= $utf2html_c;
   endif;
  endfor;
  return $utf2html_retstr;
}
28-Aug-2002 03:22
echo utf8_decode(
"Ekonomi_ve_\xc4\xb0\xc5\x9f_D\xc3xbcnyas\xc4\xb1");

Outputs: Ekonomi_ve_??_Dnyas?

This is not a bug. For example "\xc4\xb0" is decoded like this:
0xC4 = 110 00100 (110 prefix for 2 bytes)
0xB0 = 10 110000 (10 for trailing byte)
Character = 001 0011 0000 = 0x130

This U+0130 Unicode character is not defined in ISO-8859-1
(where all codes are below 0x100), so the utf8_decode() function
cannot represent it, and inserts a '?' replacement character
in the result string...

There's no alternative in the utf8_decode() function
which returns a string made of
single-byte characters.

PHP really lacks a datatype for UTF-16 (a.k.a. Unicode) strings,
unlike Java whose strings are always natively encoded
with UTF-16...

The alternative for PHP would be that it allows inserting SGML
character entities. In the above example, it could return
"&#x130;" when decoding "\xc4\xb0".

May be a future version of PHP could make strings using
double-byte UTF-16 encoding, so that Unicode could be natively
supported, but this would require adding new functions to
define the behavior of I/O functions to provide external
encode/decode capabilities when sending Unicode strings to
a file stream, or with echo and print builtins for the
standard input and output streams:

- What would be the semantic of fwrite($fp, $string)
if $string can contain any UTF-16 characters ?
- Should fwrite() truncate the highest byte of each UTF-16
character, letting the user anticipating this truncation by
performing the conversion to UTF-8 or character entities himself ?
- Should the user be able to specify an encoder/decoder object
used by all I/O operations performed on a file ?

For example:
- set_encoder($fp, 'utf8_encode') would define the PHP function
to call to encode a string.
- set_encoder($fp) or set_encoder($fp, null) would restore the
default (stripping) encoder...
- then fwrite($fp, $string) would return the number of bytes
written to the stream, which may be larger than the length of
$string...
ronen at greyzone dot com
02-Mar-2002 09:37
The following function will take a utf-8 encoded string and convert it to Unicode entities (the format is &#nnn; or &#nnnnn; with n={0..9} ).  Most browsers will display Unicode entities regardless of the encoding of the page.  Otherwise try charset=utf-8 to make sure the entities display correctly.  This works well with IE and Mozilla (tested with Mozilla 0.9.8 for X-Windos).

/**
* takes a string of utf-8 encoded characters and converts it to a string of unicode entities
* each unicode entitiy has the form &#nnnnn; n={0..9} and can be displayed by utf-8 supporting
* browsers
* @param $source string encoded using utf-8 [STRING]
* @return string of unicode entities [STRING]
* @access public
*/
function utf8ToUnicodeEntities ($source) {
   // array used to figure what number to decrement from character order value
   // according to number of characters used to map unicode to ascii by utf-8
   $decrement[4] = 240;
   $decrement[3] = 224;
   $decrement[2] = 192;
   $decrement[1] = 0;
  
   // the number of bits to shift each charNum by
   $shift[1][0] = 0;
   $shift[2][0] = 6;
   $shift[2][1] = 0;
   $shift[3][0] = 12;
   $shift[3][1] = 6;
   $shift[3][2] = 0;
   $shift[4][0] = 18;
   $shift[4][1] = 12;
   $shift[4][2] = 6;
   $shift[4][3] = 0;
  
   $pos = 0;
   $len = strlen ($source);
   $encodedString = '';
   while ($pos < $len) {
       $asciiPos = ord (substr ($source, $pos, 1));
       if (($asciiPos >= 240) && ($asciiPos <= 255)) {
           // 4 chars representing one unicode character
           $thisLetter = substr ($source, $pos, 4);
           $pos += 4;
       }
       else if (($asciiPos >= 224) && ($asciiPos <= 239)) {
           // 3 chars representing one unicode character
           $thisLetter = substr ($source, $pos, 3);
           $pos += 3;
       }
       else if (($asciiPos >= 192) && ($asciiPos <= 223)) {
           // 2 chars representing one unicode character
           $thisLetter = substr ($source, $pos, 2);
           $pos += 2;
       }
       else {
           // 1 char (lower ascii)
           $thisLetter = substr ($source, $pos, 1);
           $pos += 1;
       }

       // process the string representing the letter to a unicode entity
       $thisLen = strlen ($thisLetter);
       $thisPos = 0;
       $decimalCode = 0;
       while ($thisPos < $thisLen) {
           $thisCharOrd = ord (substr ($thisLetter, $thisPos, 1));
           if ($thisPos == 0) {
               $charNum = intval ($thisCharOrd - $decrement[$thisLen]);
               $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
           }
           else {
               $charNum = intval ($thisCharOrd - 128);
               $decimalCode += ($charNum << $shift[$thisLen][$thisPos]);
           }

           $thisPos++;
       }

       if ($thisLen == 1)
           $encodedLetter = "&#". str_pad($decimalCode, 3, "0", STR_PAD_LEFT) . ';';
       else
           $encodedLetter = "&#". str_pad($decimalCode, 5, "0", STR_PAD_LEFT) . ';';

       $encodedString .= $encodedLetter;
   }

   return $encodedString;
}

Ronen.