Programing

끊어진 UTF-8 인코딩 수정

lottogame 2020. 12. 6. 20:51
반응형

끊어진 UTF-8 인코딩 수정


잘못된 UTF-8 인코딩을 수정하는 중입니다. 현재 PHP 5와 MySQL을 사용하고 있습니다.

내 데이터베이스에는 다음과 같이 인쇄되는 잘못된 인코딩의 몇 가지 인스턴스가 있습니다. î

  • 데이터베이스 데이터 정렬은 utf8_general_ci입니다.
  • PHP가 적절한 UTF-8 헤더를 사용하고 있습니다.
  • Notepad ++는 BOM없이 UTF-8을 사용하도록 설정됩니다.
  • 데이터베이스 관리는 phpMyAdmin 에서 처리됩니다.
  • 모든 악센트 부호가있는 문자의 경우가 깨지는 것은 아닙니다.

î, ÃÂ, ü 및 기타 유사한 인스턴스를 적절한 악센트가있는 UTF-8 문자로 매핑하는 데 도움이되는 일종의 함수가 필요합니다.


나는 과거에 많은 UTF8 고장난 상황을 '수정'하려고 노력해야했는데, 불행히도 결코 쉽지 않고 종종 불가능합니다.

어떻게 파손되었는지 정확히 파악할 수없고 항상 동일한 방식으로 파손되지 않았다면 손상을 '실행 취소'하기가 어려울 것입니다.

손상을 취소하려는 경우 가장 좋은 방법은 샘플 코드 작성을 시작하는 것입니다. 여기서 'from'과 'to'의 조합을 찾을 수 있는지 확인하기 위해 mb_convert_encoding () 호출에 대한 다양한 변형을 시도합니다. 데이터를 수정합니다. 결국, 수반되는 고통 수준 때문에 이전 데이터를 수정하는 것에 대해 걱정하지 않고 앞으로 진행되는 문제를 수정하는 것이 가장 좋습니다.

그러나이 작업을 수행하기 전에 먼저이 문제를 일으키는 모든 것을 수정했는지 확인해야합니다. 이미 DB 테이블 데이터 정렬 및 편집기가 올바르게 설정되었다고 언급했습니다. 그러나 모든 것이 올바르게 UTF-8인지 확인해야하는 곳이 더 있습니다.

  • HTML을 UTF-8로 제공하고 있는지 확인하십시오.
    • header ( "콘텐츠 유형 : text / html; charset = utf-8");
  • PHP 기본 문자 세트를 utf-8로 변경하십시오.
    • ini_set ( "default_charset", 'utf-8');
  • 데이터베이스가 항상 utf-8에서 통신하지 않는 경우 utf-8 모드에 있는지 확인하기 위해 연결별로 알려야 할 수 있습니다. MySQL에서는 다음을 실행하여 수행합니다.
    • charset utf8
  • 웹 서버에 항상 UTF8로 대화를 시도하도록 지시해야 할 수 있습니다. Apache에서이 명령은 다음과 같습니다.
    • AddDefaultCharset UTF-8
  • 마지막으로, UTF-8 문제가있는 PHP 함수를 사용하고 있는지 항상 확인해야합니다. 이것은 항상 mb_ * 스타일의 '멀티 바이트 인식'문자열 함수를 사용함을 의미 합니다. 또한 htmlspecialchars ()와 같은 함수를 호출 할 때 끝에 적절한 'utf-8'charset 매개 변수를 포함하여 잘못 인코딩되지 않도록해야합니다.

전체 프로세스에서 한 단계를 놓치면 인코딩이 망가져 문제가 발생할 수 있습니다. 일단 utf-8을하는 '그루브'에 들어가면이 모든 것이 제 2의 천성이됩니다. 그리고 물론 PHP6는 getgo의 완전한 유니 코드 불만으로되어있어서 많은 것을 더 쉽게 만들 것입니다.


이중 인코딩 된 UTF8 문자 (다양한 스마트 따옴표, 대시, 아포스트로피 â € ™, 따옴표 â € œ 등)가있는 경우 mysql에서 데이터를 덤프 한 다음 다시 읽어서 잘못된 인코딩을 수정할 수 있습니다.

이렇게 :

mysqldump -h DB_HOST -u DB_USER -p DB_PASSWORD --opt --quote-names \
    --skip-set-charset --default-character-set=latin1 DB_NAME > DB_NAME-dump.sql

mysql -h DB_HOST -u DB_USER -p DB_PASSWORD \
    --default-character-set=utf8 DB_NAME < DB_NAME-dump.sql

이것은 내 이중 인코딩 UTF-8에 대한 100 % 수정이었습니다.

출처 : http://blog.hno3.org/2010/04/22/fixing-double-encoded-utf-8-data-in-mysql/


당신이 만약 utf8_encode()이미 UTF-8 다음은 여러 번 인코딩 때 깨진 보인다 인 문자열에.

toUTF8()문자열을 UTF-8로 변환 하는 함수 만들었습니다 .

문자열의 인코딩을 지정할 필요가 없습니다. Latin1 (iso 8859-1), Windows-1252 또는 UTF8 또는이 세 가지를 혼합하여 사용할 수 있습니다.

동일한 문자열에서 인코딩이 혼합 된 피드에서 직접 사용했습니다.

용법:

$utf8_string = Encoding::toUTF8($mixed_string);

$latin1_string = Encoding::toLatin1($mixed_string);

내 다른 함수 fixUTF8()는 UTF8로 여러 번 인코딩 된 경우 왜곡 된 UTF8 문자열을 수정합니다.

용법:

$utf8_string = Encoding::fixUTF8($garbled_utf8_string);

예 :

echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");

다음을 출력합니다.

Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football

다운로드 :

https://github.com/neitanod/forceutf8


인코딩이 손상된 xml 파일에 문제가 있었는데 utf-8이라고 말했지만 utf-8이 아닌 문자가 있습니다.
몇 번의 시행 착오 끝에 mb_convert_encoding()나는 그것을 고칠 수 있습니다.

mb_convert_encoding($text, 'Windows-1252', 'UTF-8')

Dan이 지적했듯이, 바이너리로 변환 한 다음 인코딩을 변환 / 수정해야합니다.

예를 들어 latin1로 저장된 utf8의 경우 다음 SQL이이를 수정합니다.

UPDATE table
   SET field = CONVERT( CAST(field AS BINARY) USING utf8)
 WHERE $broken_field_condition

나는 이것이 매우 우아하지 않다는 것을 알고 있지만 문자열이 이중 인코딩 될 수 있다고 언급 한 후에이 함수를 만들었습니다.

function fix_double encoding($string)
{
    $utf8_chars = explode(' ', 'À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö');
    $utf8_double_encoded = array();
    foreach($utf8_chars as $utf8_char)
    {
            $utf8_double_encoded[] = utf8_encode(utf8_encode($utf8_char));
    }
    $string = str_replace($utf8_double_encoded, $utf8_chars, $string);
    return $string;
}

This seems to work perfectly to remove the double encoding I am experiencing. I am probably missing some of the characters that could be an issue to others. However, for my needs it is working perfectly.


The way is to convert to binary and then to correct encoding


Another thing to check, which happened to be my solution (found here), is how data is being returned from your server. In my application, I'm using PDO to connect from PHP to MySQL. I needed to add a flag to the connection which said get the data back in UTF-8 format

The answer was

$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass, 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.

When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?


i had the same problem long time ago, and it fixed it using

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">

I found a solution after days of search. My comment is going to be buried but anyway...

  1. I get the corrupted data with php.

  2. I don't use set names UTF8

  3. I use utf8_decode() on my data

  4. I update my database with my new decoded data, still not using set names UTF8

and voilà :)


This script had a nice approach. Converting it to the language of your choice should not be too difficult:

http://plasmasturm.org/log/416/

#!/usr/bin/perl
use strict;
use warnings;

use Encode qw( decode FB_QUIET );

binmode STDIN, ':bytes';
binmode STDOUT, ':encoding(UTF-8)';

my $out;

while ( <> ) {
  $out = '';
  while ( length ) {
    # consume input string up to the first UTF-8 decode error
    $out .= decode( "utf-8", $_, FB_QUIET );
    # consume one character; all octets are valid Latin-1
    $out .= decode( "iso-8859-1", substr( $_, 0, 1 ), FB_QUIET ) if length;
  }
  print $out;
}

참고URL : https://stackoverflow.com/questions/1344692/fixing-broken-utf-8-encoding

반응형