downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

iconv_get_encoding> <icap_store_event
[edit] Last updated: Mon, 01 Nov 2010

view this page in

LIX. Iconv

Introduction

Ce module est une interface vers la bibliothèque iconv. L'extension iconv convertit des fichiers entre divers jeux de caractères. Les jeux supportés dépendent de l'implémentation de iconv() sur votre système. Notez que cette fonction ne fonctionne pas toujours bien sur tous les systèmes. Dans ce cas, ce serait une bonne idée d'installer la bibliothèque GNU libiconv.

Depuis PHP 5.0.0, cette extension dispose de beaucoup de fonctions utiles qui peuvent vous aider à écrire des scripts multilangues. Regardez les sections suivantes pour voir des nouvelles fonctionnalités.

Pré-requis

Vous n'avez besoin de rien de spécial si votre système est conforme au standard POSIX car la bibliothèque standard C fournie iconv. Dans le cas contraire, vous devez installer la bibliothèque libiconv sur votre système.

Installation

Pour pouvoir l'utiliser, vous devez compiler PHP avec l'option --with-iconv[=DIR].

Note aux utilisateurs Win32 : Afin d'activer ce module dans l'environnement Windows®, vous devez copier la bibliothèque iconv.dll ou iconv-1.3.dll (pour les versions antérieures à 4.2.1) qui est fournie avec le package PHP/Win32 dans un dossier spécifié par la variable d'environnement PATH ou dans un des dossiers systèmes de votre installation de Windows®.

Ce module fait parti de PHP depuis PHP 4, donc les bibliothèques iconv.dll et php_iconv.dll ne sont plus nécessaires.

Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Tableau 1. Options de configuration

NomPar défautModifiableHistorique
iconv.input_encoding"ISO-8859-1"PHP_INI_ALLDisponible depuis PHP 4.0.5.
iconv.output_encoding"ISO-8859-1"PHP_INI_ALLDisponible depuis PHP 4.0.5.
iconv.internal_encoding"ISO-8859-1"PHP_INI_ALLDisponible depuis PHP 4.0.5.
Pour plus de détails sur les constantes PHP_INI_*, reportez-vous à Annexe G.

Avertissement

Quelques systèmes (comme IBM AIX) utilisent "ISO8859-1" au lieu de "ISO-8859-1", cette valeur doit donc être utilisée dans les options de configuration ainsi que dans les paramètres des fonctions.

Note : L'option de configuration iconv.input_encoding n'est actuellement pas utilisée.

Types de ressources

Cette extension ne définit aucune ressource.

Constantes pré-définies

Depuis PHP 4.3.0, il est possible d'identifier durant l'exécution, la version de la bibliothèque iconv que vous utilisez.

Tableau 2. Constantes iconv

ConstanteTypeDescription
ICONV_IMPLstringLe nom de la bibliothèque
ICONV_VERSIONstringLa version de la bibliothèque

Note : La programmation de scripts dépendant de versions spécifiques, avec ces constantes, est fortement déconseillée.

Depuis PHP 5.0.0, les contantes suivantes sont également disponibles :

Tableau 3. Constantes iconv disponibles depuis PHP 5.0.0

ConstanteTypeDescription
ICONV_MIME_DECODE_STRICTentierUn masque utilisé par iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERRORentierUn masque utilisé pour iconv_mime_decode()

Voir aussi

Voir aussi les fonctions GNU Recode.

Table des matières
iconv_get_encoding --  Lit le jeu de caractères courant
iconv_mime_decode_headers --  Décode des en-têtes MIME multiples
iconv_mime_decode --  Décode un champ d'en-tête MIME
iconv_mime_encode --  Construit un en-tête MIME avec les champs field_name et field_value
iconv_set_encoding --  Modifie le jeu courant de caractères d'encodage
iconv_strlen --  Retourne le nombre de caractères d'une chaîne
iconv_strpos --  Trouve la position de la première occurence de needle dans haystack
iconv_strrpos --  Trouve la position de la dernière occurence d'un élément dans une chaîne, à partir d'un offset
iconv_substr --  Retourne une partie de chaîne iconv
iconv -- Convertit une chaîne dans un jeu de caractères
ob_iconv_handler --  Gestionnaire de sortie pour maîtriser le jeu de caractères de sortie


iconv_get_encoding> <icap_store_event
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Iconv
Martin Petrov 19-Oct-2009 02:05
This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.

<?php
function cp1251_to_utf8($s)
  {
  if ((
mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
    {
   
$c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
    for(
$i=0; $i<strlen($s); $i++)
      {
     
$c=ord($s[$i]);
      if (
$c>=192 and $c<=239) $t.=$c208.chr($c-48);
      elseif (
$c>239) $t.=$c209.chr($c-112);
      elseif (
$c==184) $t.=$c209.$c209;
      elseif (
$c==168)    $t.=$c208.$c129;
      else
$t.=$s[$i];
      }
    return
$t;
    }
  else
    {
    return
$s;
    }
   }

function
utf8_to_cp1251($s)
  {
  if ((
mb_detect_encoding($s,'UTF-8,CP1251')) == "UTF-8")
    {
    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;
    }
  else
    {
    return
$s;
    }
  }
?>
nospam at nihonbunka dot com 15-May-2008 08:40
iconv does not convert to sjis tildes unless you do something like this

<?PHP
$string
= 'where are the (~) (~) tildes?'; // This is what we start off with, you can put any string in here that contains problematic characters in utf8 format
echo ('this is what we start with = '.$string.'<BR />'); //print string at start
$conv_str = iconv('utf-8','shift-jis'.'//TRANSLIT',$string);
echo (
'this is not working = '.$conv_str.'<BR />'); //Just to show that this is not working.

$rstring = preg_replace ('/~/','1bytetilde',$string);   //replace before conversion
echo ('this is modified string here = '.$rstring.'<BR />'); //This is the modified string

$conv_str2 = iconv('utf-8','shift-jis'.'//TRANSLIT',$rstring); //convert modified string
$rereplace=chr(126); //$rereplace is now a one byte tilde in shift_jis
$rerstring = preg_replace ('/1bytetilde/',$rereplace,$conv_str2); //rereplace with tildes
echo ('this is the correct result = '.$rerstring.'<BR />'); //the correct result
?>
Erel Segal - Rent a Brain 25-Mar-2007 11:32
Note that my mysql_iconv will not translate correctly the Hebrew dotting symbols (Niqqud) - they will be converted into question marks.

Here is a straightforward (and not very efficient) solution:

<?php
function utf8_to_windows1255($utf8) {
   
$windows1255 = "";
   
$chars = preg_split("//",$utf8);
    for (
$i=1; $i<count($chars)-1; $i++) {
       
$prefix = ord($chars[$i]);
       
$suffix = ord($chars[$i+1]);
       
//print ("<p>$prefix $suffix");
       
if ($prefix==215) {
           
$windows1255 .= chr($suffix+80);
           
$i++;
        }
        elseif (
$prefix==214) {
           
$windows1255 .= chr($suffix+16);
           
$i++;
        }
        else {
           
$windows1255 .= $chars[$i];
        }
    }
    return
$windows1255;
}
?>
Fabian Ketchup 13-Sep-2006 06:00
// Simple file translation.

$FileToconvert = "menu.xml";
$FileConverted = "menu2.xml";

echo "Converting $FileToconvert ...";

file_put_contents($FileConverted, iconv("ISO-8859-1","UTF-8",file_get_contents($FileToconvert)));

echo "File converted in $FileConverted";
nod at mobi dot kz 17-Jul-2006 07:17
If you need convert string from Windows-1251 to 866. Some characters of 1251 haven't representation on DOS 866. For example, long dash -- chr(150) will be converted to 0, after that iconv finish his work and other charactes  will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).

Use this:

//$text  -  input text in windows-1251
//$cout  -  output text in 866 (cp866, dos ru ascii)

for($i=0;$i<strlen($text);$i++) {
    $ord=ord($text[$i]);
    if($ord>=192&&$ord<=239) $cout.=chr($ord-64);
    elseif($ord>=240&&$ord<=255) $cout.=chr($ord-16);
    elseif($ord==168) $cout.=chr(240);
    elseif($ord==184) $cout.=chr(241);
    elseif($ord==185) $cout.=chr(252);
    elseif($ord==150||$ord==151) $cout.=chr(45);
    elseif($ord==147||$ord==148||$ord==171||$ord==187) $cout.=chr(34);
    elseif($ord>=128&&$ord<=190) $i=$i; //нет представления данному символу
    else $cout.=chr($ord);
}
andrej009 16-Mar-2006 04:22
There's one more special german character: ß (sometimes displayed as Ϋ)

so: case 159: $out .= "ß";break;
08-Nov-2005 12:05
But this is a very slow method to convert this:

// function to change german umlauts into ue, oe, etc.
function cv_input($str){

Better try this:
$tr = array(chr(xyz) => '', chr(160) => ' '); // Just a simple example, put all your characters in there
$string = strtr($string, $tr);
Christophe Lienert 27-Sep-2005 02:09
In addition to Godfather's note below, you may find this function useful just as well.

// function to change german umlauts into ue, oe, etc.
function cv_input($str){
      $out = "";
      for ($i = 0; $i<strlen($str);$i++){
           $ch= ord($str{$i});
           switch($ch){
                case 195: $out .= "";break;    
                case 164: $out .= "ae"; break;
                case 188: $out .= "ue"; break;
                case 182: $out .= "oe"; break;
                case 132: $out .= "Ae"; break;
                case 156: $out .= "Ue"; break;
                case 150: $out .= "Oe"; break;
                default : $out .= chr($ch) ;
           }
      }
      return $out;
}
The Godfather 15-Dec-2004 05:36
With this function you can translate the german Symbols from the character set UTF-8 in windows-1252.

function convert_text($str){
  $out = '';
  for ($i = 0; $i<strlen($str);$i++){
   $ch = ord($str{$i});
   switch($ch){
         case 252: $out .= chr(129);break; //u Umlaut
         case 220: $out .= chr(154);break;//U Umlaut
         case 228: $out .= chr(132);break;//a Umlaut 
         case 196: $out .= chr(142);break;//A Umlaut
         case 214: $out .= chr(153);break;//O Umlaut 
         case 246: $out .= chr(148);break;//o Umlaug
         case 223: $out .= chr(225);break;//SZ
         default : $out .= chr($ch) ;
   }
  }
  return $out;
}
tokiee at hotmail dot com 19-Aug-2004 01:40
iconv now has been built-in, at least in PHP >= 5.0.1 for win32. You don't have to modify php.ini for this. Actually you should not. And clearly, libiconv does not need to be installed.
thierry.bo 23-Dec-2003 02:26
Windows users.

Personaly I leaved all php dlls in \php\dlls\ directory, just adding this path to my system path, and iconv.dll supplied with php 4.3.2 works fine, also leaving supplied php_iconv.dll in my \php\extensions\ directory. This was working fine with Apache and Omnihttpd server I use.

As soon I installed IIS on the same server, php complained about not finding php_iconv.dll in the extensions directory. In fact PHP with IIS loads all extensions in my \php\extensions directory correctly, except php_iconv.dll.
Although iconv.dll is in my system path, the only way to load php_iconv.dll was to copy iconv.dll file in \%winnt\system32 directory. With other servers, iconv.dll can be in anywhere in the system path.
13-Sep-2002 05:23
I'm not sure how recent version of
glibc 2.x Slackware 7.x/8.x comes with, but
it's very likely that it comes with glibc 2.2.x.
In that case, you don't have to bother at all to
install libiconv in /usr/local. iconv(3) in glibc 2.2.x
is very good (thanks to Ulrich Drepper and
Bruno Haible. the latter is the author of libiconv).
libiconv is very handy for those outdated/non-standard-compliant Unix
and non-Unix systems that don't have
sufficiently good iconv(3) in their C library.
elk at NOSPAMmodel-fx dot com 25-Jul-2002 08:39
To compile libiconv under Slackware 7.0 or 8.0 without errors (either with the apache module of PHP or the CGI version), you must specify the full path of the libiconv installation.

Exemple :

       --with-iconv=/usr/local

 
show source | credits | sitemap | contact | advertising | mirror sites