Textlocal Logo

API Documentation

Unicode

SMS typically uses the GSM 03.38 character set, but can also be in UCS-2. If a message is in UCS-2, you can use these helper functions to convert it into the more useful UTF-8:

<?php

function unicodeMessageDecode($message) {
    if (stripos($message, '@U') !== 0) {
        return $message;
    }
    $message = substr($message, 2);
    $_message = hex2bin($message);
    $message = mb_convert_encoding($_message, 'UTF-8', 'UCS-2');
    return $message;
}

function unicodeMessageEncode($message){
    return '@U' . strtoupper(bin2hex(mb_convert_encoding($message, 'UCS-2','auto')));
}

// hex2bin requires PHP >= 5.4.0.
// If, for whatever reason, you are using a legacy version of PHP, you can implement hex2bin with this function:

if (!function_exists('hex2bin')) {
    function hex2bin($hexstr) {
        $n = strlen($hexstr);
        $sbin = "";
        $i = 0;
        while ($i < $n) {
            $a = substr($hexstr, $i, 2);
            $c = pack("H*", $a);
            if ($i == 0) {
                $sbin = $c;
            } else {
               $sbin .= $c;
            }
            $i += 2;
         }
         return $sbin;
    }
}