Search code examples
phpencodingutf-8declare

PHP declare encoding


On the declare() page of the PHP manual:

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>
  1. What does this do exactly? How is the behaviour of the script affected by this directive?

  2. How does this differ from setting the directives mbstring.internal_encoding (before PHP 5.6) and default_charset (as of PHP 5.6) or using the mb_internal_encoding() function?

(I use both PHP 5.3 and 5.5. Currently my files are saved in UTF-8 and I send the header Content-Type: text/html; charset=utf-8 when serving HTML files.)


Solution

  • PHP 5.6 comes with a new default charset directive set to UTF-8, in some case this may be a problem with pages served in metatag as latin1, you can override this directive by calling ini_set('default_charset', 'iso-8859-1') in your scripts.

    For doing that put on each php file you want to be coded to latin1 this piece of code at the beginning of your scripts:

    example: index.php

    <?php
      $server_root = realpath($_SERVER["DOCUMENT_ROOT"]);
      $config_serv = "$server_root/php/config.php";
      include("$config_serv");
    ?>
    

    Then create a folder "php" under your root website and put this piece of code into config.php:

    example: config.php

    <?php
      ##########################################################################
      # Server Directive - Override default_charset utf-8 to latin1 in php.ini #
      ##########################################################################
      @ini_set('default_charset', 'ISO-8859-1');
    ?>
    

    If your php.ini is set to latin1 (ISO-8859-1) and you want serve a utf-8 (unicode) page you can force encoding using the same way but putting instead of iso-8859-1, utf-8. Look at that:

    example: config.php

    <?php
      ##########################################################################
      # Server Directive - Override default_charset latin1 to utf-8 in php.ini #
      ##########################################################################
      @ini_set('default_charset', 'UTF-8');
    ?>
    

    I hope you find my answer useful, I solved my problem in this way!