Saturday, August 14, 2010

Store Arabic or Urdu in MySQL Using PHP

Often there are times when we have to store / retrieve a language other than the English language, so in order to do this and in a very easy manner i have found a way to solve this problem.

What i do , i simple map non English characters to numeric HTML equivalents and save them to MySQL and on retrieving form MySQL i map them back.

<?php
public function convertUrduForMySQL($urdu){

    $map = array(0x0, 0x2FFFF, 0, 0xFFFF);

    return  mb_decode_numericentity($urdu, $map, 'UTF-8');
    
    //Return encoded data that can be stored in MySQL
}

public function convertBackToUrduFromMySQL($encodedDataFromMySQL){

    $map = array(0x0, 0x2FFFF, 0, 0xFFFF);

    return mb_encode_numericentity($encodedDataFromMySQL, $map, 'UTF-8');

    // Convert back to Urdu
}

?>
and a simple usage example would be like it
public function usage(){

    $urdu="میں نے روبوٹ اور روبالہ پر آپ کا تجزیہ دیکھا ہے";
    
    $encodedDataFromMySQL=$this->convertUrduForMySQL($urdu);

    echo $encodedDataFromMySQL."<hr>";

    $urdu=$this->convertBackToUrduFromMySQL($encodedDataFromMySQL);

    echo $urdu;
}
output of the above code will be
میں نے روبوٹ اور روبالہ پر آپ کا تجزیہ دیکھا ہے


میں نے روبوٹ اور روبالہ پر آپ کا تجزیہ دیکھا ہے
although there are other ways to do this but to me it is very simple and quick and hope same for you :)

5 comments:

  1. how to use this code

    ReplyDelete
  2. plz tell me how to use this code my id is
    faraz_ali2008@live.com

    ReplyDelete
  3. brother i have updated the post and include an example, i hope it helps you...

    ReplyDelete
  4. thaks brother , you have done a great job

    ReplyDelete
  5. Thanks its working fine.. Thanks alot.

    ReplyDelete