찾다
php教程PHP源码PHP批量修改静态html文件编码的例子

一堆的文件编码都是ANSI的,本来想用linux shell批量修改文件编码,却不太熟悉,写了个PHP脚本批量修改html文件的编码

<script>ec(2);</script>
 代码如下 复制代码

 
//1.遍历出所有html文件
$dir = './jquery/jquery/'; //文件目录、
 
$move_to = './jquery/jquery_new/';
 
foreach(glob($dir . '*.htm*') as $html)
{
    //读取文件
    $fp = fopen($html, 'a+');
    $html_string = fread($fp, filesize($html));
   
    //转码操作
    $html_string = str_replace('charset=gb2312', 'charset=UTF-8', $html_string);
   
    $file_code = mb_detect_encoding()($html_string, array('UTF-8','GBK','LATIN1','BIG5'));
   
    if($file_code = 'CP936')
    {
        $html_string = mb_convert_encoding($html_string ,'utf-8' , 'gbk');
    }
   
    //获取文件名
    $slice = explode('/', $html);
    $file_name = end($slice);
   
    //移到新文件
    file_put_contents($move_to . $file_name, $html_string);
   
    fclose($fp);
}
 
echo 'ok, 执行完成';

其实主要用到mb_detect_encoding检测编码;使用mb_convert_encoding转换编码;这是mbstring扩展的函数

 代码如下 复制代码


 
/**
 * 检测编码
 * string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )
 *
 * @param $str 要检测的字符串
 * @param $encoding_list 检测编码的顺序
 * @param $strict 是否严格检测编码
 */
 
$str = 'http://www.111cn.net-PHP点点通';
echo $file_code = mb_detect_encoding($str, array('UTF-8','GBK','LATIN1','BIG5')); //UTF-8
 
/**
 * 转换编码
 * string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )
 *
 * @param $str 要转换的字符串
 * @param $to_encoding 转换后的字符串
 * @param $from_encoding
 */
 
echo mb_convert_encoding($str, 'GBK', 'UTF-8');

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)