Php detection data encoding type

Source: Internet
Author: User
Php detection file encoding type define (UTF32_BIG_ENDIAN_BOM & nbsp;, chr (0x00 ). chr (0x00 ). chr (0xFE ). chr (0xFF); define (UTF32_LITTLE_ENDIAN_BOM, chr (0xFF ). chr (0xFE ). chr (0x00) php detects file encoding types
Define ('utf32 _ BIG_ENDIAN_BOM ', chr (0x00). chr (0x00). chr (0xFE). chr (0xFF ));
Define ('utf32 _ LITTLE_ENDIAN_BOM ', chr (0xFF). chr (0xFE). chr (0x00). chr (0x00 ));
Define ('utf16 _ BIG_ENDIAN_BOM ', chr (0xFE). chr (0xFF ));
Define ('utf16 _ LITTLE_ENDIAN_BOM ', chr (0xFF). chr (0xFE ));
Define ('utf8 _ BOM ', chr (0xEF). chr (0xBB). chr (0xBF ));

Function detect_utf_encoding ($ text ){
$ First2 = substr ($ text, 0, 2 );
$ First3 = substr ($ text, 0, 3 );
$ First4 = substr ($ text, 0, 3 );

If ($ first3 = UTF8_BOM) return 'utf-8 ';
Elseif ($ first4 = UTF32_BIG_ENDIAN_BOM) return 'utf-32BE ';
Elseif ($ first4 = UTF32_LITTLE_ENDIAN_BOM) return 'utf-32le ';
Elseif ($ first2 = UTF16_BIG_ENDIAN_BOM) return 'utf-16BE ';
Elseif ($ first2 = UTF16_LITTLE_ENDIAN_BOM) return 'utf-16le ';
}

Function getFileEncoding ($ str ){
$ Encoding = mb_detect_encoding ($ str );
If (empty ($ encoding )){
$ Encoding = detect_utf_encoding ($ str );
}
Return $ encoding;
}
$ File = 'text1.txt ';
Echo getFileEncoding (file_get_contents ($ file); // output ASCII
Echo '';

$ File = 'text2.txt ';
Echo getFileEncoding (file_get_contents ($ file); // output UTF-8
Echo '';
$ File = 'text3.txt ';
Echo getFileEncoding (file_get_contents ($ file); // output UTF-16LE
Echo '';

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.