php function convert utf-8 to tis-620 and tis-620 to utf-8

17 June 2014 4:26 AM php, Web Server , , , ,

function utf8_to_tis620

This function converts the string from utf-8 to tis-620. For example, the webpage use encoding utf-8 but table charset is ​​tis-620. So i must convert strings to tis620-strings before saving by using this custom function or built-in function to your discretion. At my experience, i have use built-in function for Thai language conversion but possess a flaw on some figures. Therefore i change to refer to this custom function instead.

function utf8_to_tis620($string) {
   $str = $string;
   $res = "";
   for ($i = 0; $i < strlen($str); $i++) {
      if (ord($str[$i]) == 224) {
        $unicode = ord($str[$i+2]) & 0x3F;
        $unicode |= (ord($str[$i+1]) & 0x3F) << 6;
        $unicode |= (ord($str[$i]) & 0x0F) << 12;
        $res .= chr($unicode-0x0E00+0xA0);
        $i += 2;
      } else {
        $res .= $str[$i];
      }
   }
   return $res;
}

function tis620_to_utf8

This function converts the string of tis-620 to utf8, such as data stored in the table is tis620 but when display on page it as utf-8 (as is standard encoding on webpage today).

function tis620_to_utf8($in) {
   $out = "";
   for ($i = 0; $i < strlen($in); $i++)
   {
     if (ord($in[$i])
       $out .= $in[$i];
     else
       $out .= "&#" . (ord($in[$i]) - 161 + 3585) . ";";
   }
   return $out;
}

@Credit: MR2T.COM