PHP实现文件读写中英文数据分割插入数组代码

<?php

$fp = fopen("D:game我的世界.txt", "r");
$arr1=array();
$j=0;
if($fp)
{
    for($i=1;! feof($fp);$i++)
    {
        $cle=fgets($fp);
        $arr1[$j++]=$cle;
    }
    $cou1=count($arr1);
}
else
{
    echo "打开文件失败";
}
fclose($fp);

$arr2=array();

$text = file_get_contents("D:game我的世界英文.txt");
//$encodType = mb_detect_encoding($text);
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));
$first2 = substr($text, 0, 2);
$first3 = substr($text, 0, 3);
$first4 = substr($text, 0, 3);
$encodType = "";
if ($first3 == UTF8_BOM)
$encodType = 'UTF-8 BOM';
else if ($first4 == UTF32_BIG_ENDIAN_BOM)
$encodType = 'UTF-32BE';
else if ($first4 == UTF32_LITTLE_ENDIAN_BOM)
$encodType = 'UTF-32LE';
else if ($first2 == UTF16_BIG_ENDIAN_BOM)
$encodType = 'UTF-16BE';
else if ($first2 == UTF16_LITTLE_ENDIAN_BOM)
$encodType = 'UTF-16LE';
//下面的判断主要还是判断ANSI编码的·
if ($encodType == '') {//即默认创建的txt文本-ANSI编码的
$content = iconv("GBK", "UTF-8", $text);
} else if ($encodType == 'UTF-8 BOM') {//本来就是UTF-8不用转换
$content = $text;
} else {//其他的格式都转化为UTF-8就可以了
$content = iconv($encodType, "UTF-8", $text);
}

$arr2 = explode("
",$content);

$cou2=count($arr2);

$gt=1;
$gc=0;
for($lt=0;$lt<$cou1;$lt++)
{
    $longtext = $arr2[$gt];
    array_splice($arr1, $gc, 0, $longtext);
    $gt+=3;
    $gc+=4;
}

$arry=$arr1;
$couy=count($arry);
$wfp = fopen("test.txt", "w");//文件被清空后再写入
if($wfp)
{
    $j=0;
    for($i=1;$i<=$couy;$i++)
    {
        $flag=fwrite($wfp,$arry[$j++]."
");
        if(!$flag)
        {
            echo "写入文件失败<br>";
            break;
        }
    }
}
else
{
    echo "打开文件失败";
}
fclose($wfp);

?>

<!DOCTYPE html>
<html>
<head>
    <title>我的世界物品英文大全</title>
</head>
<body>

<?php 

echo '<table border="1" align="center">';
    echo '<caption><h1>我的世界物品英文大全</h1></caption>';
    echo '<tr bgcolor="#dddddd">';
    echo '<th>中文名称</th><th>数字ID</th><th>英文名称</th><th>官方名称</th>';
    echo '</tr>';
    $i=0;
    $j=4;
    for($row=0;$row<$couy/4;$row++)
    {
        echo '<tr>';
        for(;$i<$j;$i++)
        {
            echo '<td>'.$arry[$i].'</td>';
        }
        echo '</tr>';
        $j+=4;
    }
    echo '</table>';

 ?> 

</body>
</html>
原文地址:https://www.cnblogs.com/wlei5206/p/12592831.html