Convert any string to UTF-8 without knowing the original character set

Asked

Viewed 1,057 times

12

I need a function or class that ensures that data sent from a form (from anywhere in the world) go to the bank in UTF-8 encoding.

I tried to, $string = iconv(mb_detect_encoding($text), "UTF-8", $text); but has problems (if the input is 'nation' it returns 'in').

I tried to $string = mb_convert_encoding($text, "UTF-8"); but also has problems returns no§

1 answer

8


Has a library available that plays this role without you having to be in doubt between which function of the PHP use to convert special character.

That one library works only on the PHP >= 5.3

Clicking here to go to the repository on GITHUB.

Use as follows:

<?php
use \ForceUTF8\Encoding;

echo Encoding::toUTF8("nação");
# retorna: nação

echo Encoding::fixUTF8("nação");
# retorna: nação

[EDIT]

Or, as follows:

 <?php
 require_once "forceUTF8/Encoding.php";
 echo \ForceUTF8\Encoding::fixUTF8("nação");

Or

 <?php
 require_once "forceUTF8/Encoding.php";
 $utf8 = new Encoding;
 echo $utf8::fixUTF8("nação");
  • 1

    gave 2 errors PHP Warning: Unexpected Character in input: '' (ASCII=92) state=1 in.... on line 4 PHP Parse error: syntax error, Unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING .... on line 4 Line 4= use Forceutf8 Encoding;

  • I edited the answer with an option that might work in your case.

  • PHP Warning: Unexpected Character in input: '' (ASCII=92) state=1 in ..... PHP Parse error: syntax error, Unexpected T_STRING, expecting ',' or ';' ... on line 8 Line 8 >> echo Forceutf8 Encoding::fixUTF8("Naã§");

  • echo Encoding::fixUTF8("Naã§Ã"); and gave error PHP Parse error: syntax error, Unexpected T_STRING in .... Encoding.php on line 36 On line 36 of the Encoding file we have namespace Forceutf8;

  • @Leo Caracciolo What’s your version PHP ?

  • @ William Novak Version 5.2.17 .... ;)

  • Leo, unfortunately namespaces is only available in versions >= 5.3 of PHP.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.