PHP test File Encoding Method Example _php instance

Source: Internet
Author: User
Tags md5

On the detection of file encoding, Baidu is a lot of it is, but there is no use, many people suggest mb_detect_encoding detection, but I do not know why I did not succeed, nothing output, see someone wrote an enhanced version, with the BOM to judge, I decisively ignored, this thing is completely unreliable , and finally based on the example in the PHP manual below the mb_detect_encoding function, wrote a test function,
It also includes a function to automatically detect the encoding and read the file by pointing code, and the source is presented.

Copy Code code as follows:

<?php
/**
* Detection file encoding
* @param string $file file path
* @return String|null return the encoded name or null
*/
function detect_encoding ($file) {
$list = Array (' GBK ', ' UTF-8 ', ' utf-16le ', ' utf-16be ', ' iso-8859-1 ');
$str = file_get_contents ($file);
foreach ($list as $item) {
$tmp = mb_convert_encoding ($str, $item, $item);
if (MD5 ($tmp) = = MD5 ($STR)) {
return $item;
}
}
return null;
}

/**
* Automatically parse encoded read file
* @param string $file file path
* @param string $charset Read encoding
* @return string to return read content
*/
function Auto_read ($file, $charset = ' UTF-8 ') {
$list = Array (' GBK ', ' UTF-8 ', ' utf-16le ', ' utf-16be ', ' iso-8859-1 ');
$str = file_get_contents ($file);
foreach ($list as $item) {
$tmp = mb_convert_encoding ($str, $item, $item);
if (MD5 ($tmp) = = MD5 ($STR)) {
Return mb_convert_encoding ($str, $charset, $item);
}
}
Return "";
}

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.