인코딩 검사 및 모든 UTF-8 제작

9151 단어
Detect encoding and make everything UTF-8
I'm reading out lots of texts from various RSS feeds and inserting them into my database. 다양한 RSS Feed에서 많은 텍스트를 읽고 데이터베이스에 삽입하고 있습니다.
Of course, there are several different character encodings used in the feeds, eg UTF-8 and ISO 8859-1. 물론 개요에는 UTF-8과 ISO 8859-1과 같은 몇 가지 다른 문자 인코딩이 사용되었다.
Unfortunately, there are sometimes problems with the encodings of the texts. 불행하게도, 텍스트의 인코딩에 때때로 문제가 발생할 수 있다.Example:예:
  • The "ß"in "Fußball"should look like this in my database: "Ÿ"."Fube ball"의"be ball"은 내 데이터베이스에서 다음과 같이 보여야 합니다.Ÿ”. If it is a "Ÿ, it is displayed correctly. 만약 그것이 "Â"이라면 정확하게 표시됩니다.
  • Sometimes, the "ß"in "Fußball"looks like this in my database: "ß"."Fube ball"의"Fube ball"은 가끔 내 데이터베이스에서 이렇게 보입니다.Ÿ”. Then it is displayed wrongly, of course. 그리고 당연히 오류가 나타날 것이다.
  • In other cases, the "ß"is saved as a "ß"- so without any change. 다른 경우 "ß"은 "ß"로 저장되므로 변경할 필요가 없습니다.Then it is also displayed wrongly. 그리고 그것도 오류를 나타낼 것이다.

  • What can I do to avoid the cases 2 and 3? 상황 2와 상황 3을 어떻게 피해야 합니까?
    How can I make everything the same encoding, preferably UTF-8? 어떻게 모든 내용을 같은 인코딩으로 사용하는가, 가장 좋은 것은 UTF-8입니까?When must I use utf8_encode() , when must I use utf8_decode() (it's clear what the effect is but when must I use the functions?) and when must I do nothing with the input? 언제 사용해야 합니까utf8_encode(), 언제 사용해야 합니까utf8_decode()(어떤 효과가 나타날지 뻔하지만 언제 이 함수들을 사용해야 합니까?),언제 입력을 실행하지 않습니까?
    How do I make everything the same encoding? 어떻게 모든 내용을 같은 인코딩을 가지게 합니까?Perhaps with the function mb_detect_encoding() ? 그렇게 지도 모른다, 아마, 아마...Can I write a function for this? 이것 괜찮아요?So my problems are: 그래서 제 질문은:
  • How do I find out what encoding the text uses? 어떻게 문자가 사용하는 인코딩 방식을 찾아냅니까?
  • How do I convert it to UTF-8 - whatever the old encoding is? 이전 인코딩과 상관없이 UTF-8로 어떻게 변환합니까?

  • Would a function like this work? 이런 기능이 작용할까요?
    function correct_encoding($text) {
        $current_encoding = mb_detect_encoding($text, 'auto');
        $text = iconv($current_encoding, 'UTF-8', $text);
        return $text;
    }
    

    I've tested it, but it doesn't work. 나는 이미 테스트를 했지만 소용이 없다.What's wrong with it? 그것은 무슨 문제가 생겼습니까?
    #1층
    참조:https://stackoom.com/question/3owD/인코딩 검사 및 모든 UTF 작성
    #2층
    I had same issue with phpQuery(ISO-8859-1 instead of UTF-8) and this hack helped me: phpQuery에서 같은 질문(ISO-8859-1 UTF-8 아님)을 받았는데 이 hack이 도움이 됐어요.
    $html = '' . $html;
    
    mb_detect_encoding() , mb_internal_encoding('UTF-8') , phpQuery::newDocumentHTML($html, 'utf-8') and other manipulations didn't take any effect. mbstring.internal_encoding,mb_internal_encoding('UTF-8'),phpQuery::newDocumentHTML($html, 'utf-8') 및 기타 조작은 모두 무효입니다.
    #3층
    Get encoding from headers and convert it to utf-8. 제목에서 인코딩을 받아서utf-8로 변환합니다.
    $post_url='http://website.domain';
    
    /// Get headers 
    function get_headers_curl($url) 
    { 
        $ch = curl_init(); 
    
        curl_setopt($ch, CURLOPT_URL,            $url); 
        curl_setopt($ch, CURLOPT_HEADER,         true); 
        curl_setopt($ch, CURLOPT_NOBODY,         true); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_TIMEOUT,        15); 
    
        $r = curl_exec($ch); 
        return $r; 
    }
    $the_header = get_headers_curl($post_url);
    /// check for redirect /
    if (preg_match("/Location:/i", $the_header)) {
        $arr = explode('Location:', $the_header);
        $location = $arr[1];
    
        $location=explode(chr(10), $location);
        $location = $location[0];
    
    $the_header = get_headers_curl(trim($location));
    }
    /// Get charset /
    if (preg_match("/charset=/i", $the_header)) {
        $arr = explode('charset=', $the_header);
        $charset = $arr[1];
    
        $charset=explode(chr(10), $charset);
        $charset = $charset[0];
        }
    ///
    // echo $charset;
    
    if($charset && $charset!='UTF-8') { $html = iconv($charset, "UTF-8", $html); }
    

    #4층
    I know this is an older question, but I figure a useful answer never hurts. 나는 이것이 비교적 오래된 문제라는 것을 알고 있지만, 나는 유용한 답안이 영원히 당신을 고통스럽게 하지 않을 것이라고 생각한다.I was having issues with my encoding between a desktop application, SQLite, and GET/POST variables. 데스크톱 응용 프로그램에서 SQLite와 GET/POST 변수 사이의 인코딩에 문제가 있습니다.Some would be in UTF-8, some would be in ASCII, and basically everything would get screwed up when foreign characters got involved. 어떤 것은 UTF-8을 사용하고, 어떤 것은 ASCII를 사용하며, 기본적으로 외부 문자와 관련이 있을 때 모든 내용을 망칠 수 있다.
    Here is my solution. 이것은 나의 해결 방안이다.It scrubs your GET/POST/REQUEST (I omitted cookies, but you could add them if desired) on each page load before processing. 처리하기 전에, 페이지를 불러올 때마다 GET/POST/REQUEST (쿠키는 생략했지만 필요에 따라 추가할 수 있습니다.)It works well in a header. 그것은 헤더에서 잘 작동한다.PHP will throw warnings if it can't detect the source encoding automatically, so these warnings are suppressed with @'s. PHP가 소스 인코딩을 자동으로 감지하지 못하면 경고를 보내므로 이 경고는 @로 억제됩니다.
    //Convert everything in our vars to UTF-8 for playing nice with the database...
    //Use some auto detection here to help us not double-encode...
    //Suppress possible warnings with @'s for when encoding cannot be detected
    try
    {
        $process = array(&$_GET, &$_POST, &$_REQUEST);
        while (list($key, $val) = each($process)) {
            foreach ($val as $k => $v) {
                unset($process[$key][$k]);
                if (is_array($v)) {
                    $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = $v;
                    $process[] = &$process[$key][@mb_convert_encoding($k,'UTF-8','auto')];
                } else {
                    $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = @mb_convert_encoding($v,'UTF-8','auto');
                }
            }
        }
        unset($process);
    }
    catch(Exception $ex){}
    

    #5층
    A really nice way to implement an mbstring.internal_encoding -function can be found on php.net:php.net에서 isUTF8 기능을 실현하는 아주 좋은 방법을 찾았습니다.
    function isUTF8($string) {
        return (utf8_encode(utf8_decode($string)) == $string);
    }
    

    #6층
    If you apply isUTF8 to an already UTF-8 string, it will return garbled UTF-8 output. utf8_encode() 를 이미 존재하는 UTF-8 문자열에 적용하면, 혼란된 UTF-8 출력을 되돌려줍니다.
    I made a function that addresses all this issues. 나는 이 모든 문제들을 해결하는 기능을 했다.It´s called utf8_encode() . 이른바 Encoding::toUTF8()이다.
    You don't need to know what the encoding of your strings is. 문자열의 인코딩이 무엇인지 알 필요가 없습니다.It can be Latin1 ( ISO 8859-1) , Windows-1252 or UTF-8, or the string can have a mix of them. Latin1(ISO 8859-1), Windows-1252 또는 UTF-8 또는 문자열을 혼합하여 사용할 수 있습니다.Encoding::toUTF8() will convert everything to UTF-8. Encoding::toUTF8() 모든 컨텐트가 UTF-8로 변환됩니다.
    I did it because a service was giving me a feed of data all messed up, mixing UTF-8 and Latin1 in the same string. 내가 이렇게 한 것은 어떤 서비스가 나의 데이터 전송을 혼란스럽게 하고 같은 문자열에 UTF-8과 Latin1을 혼합했기 때문이다.
    Usage:사용법:
    require_once('Encoding.php');
    use \ForceUTF8\Encoding;  // It's namespaced now.
    
    $utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
    
    $latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);
    

    Download:다운로드:
    https://github.com/neitanod/forceutf8 https://github.com/neitanod/forceutf8
    I've included another function, Encoding::toUTF8() , which will fix every UTF-8 string that looks garbled. 혼란스러워 보이는 모든 UTF-8 문자열을 복구하는 또 다른 함수Encoding::fixUFT8()가 포함되어 있습니다.
    Usage:사용법:
    require_once('Encoding.php');
    use \ForceUTF8\Encoding;  // It's namespaced now.
    
    $utf8_string = Encoding::fixUTF8($garbled_utf8_string);
    

    Examples:예:
    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");
    

    will output:출력:
    Fédération Camerounaise de Football
    Fédération Camerounaise de Football
    Fédération Camerounaise de Football
    Fédération Camerounaise de Football
    

    I've transformed the function ( Encoding::fixUFT8() ) into a family of static functions on a class called forceUTF8 . 나는 이미 함수 ((EncodingforceUTF8 라고 불리는 클래스의 정적 함수 시리즈로 바꾸었다.The new function is Encoding . 새 함수는 Encoding::toUTF8()입니다.

    좋은 웹페이지 즐겨찾기