在 PHP 中拆分文本文件 [英] Split a text file in PHP

查看:35
本文介绍了在 PHP 中拆分文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 按字符数将大型文本文件拆分为单独的文件?因此,每 1000 个字符拆分的 10,000 个字符文件将拆分为 10 个文件.另外,我可以在找到句号后才能拆分吗?

How can I split a large text file into separate files by character count using PHP? So a 10,000 character file split every 1000 characters would be split into 10 files. Further, can I split only after a full stop is found?

谢谢.

更新 1:我喜欢 zombats 代码,我删除了一些错误并提出了以下内容,但有没有人知道如何仅在句号停止后拆分?

UPDATE 1: I like zombats code and I removed some errors and have come up with the following, but does anyone know how to only split after a full stop?

$i = 1;
    $fp = fopen("test.txt", "r");
    while(! feof($fp)) {
        $contents = fread($fp,1000);
        file_put_contents('new_file_'.$i.'.txt', $contents);
        $i++;
    }

更新2:我接受了僵尸的建议并将代码修改为下面的代码,它似乎有效 -

UPDATE 2: I took zombats suggestion and modified the code to that below and it seems to work -

$i = 1;
    $fp = fopen("test.txt", "r");
    while(! feof($fp)) {
        $contents = fread($fp,20000);
        $contents .= stream_get_line($fp,1000,".");
        $contents .=".";

        file_put_contents("Split/".$tname."/"."new_file_".$i.".txt", $contents);
        $i++;
    }

推荐答案

您应该能够使用基本的 fread 轻松完成此操作().您可以指定要读取的字节数,因此读取确切数量并将其输出到新文件很简单.

You should be able to accomplish this easily with a basic fread(). You can specify how many bytes you want to read, so it's trivial to read in an exact amount and output it to a new file.

尝试这样的事情:

$i = 1;
$fp = fopen("test.txt",'r');
while(! feof($fp)) {
    $contents = fread($fp,1000);
    file_put_contents('new_file_'.$i.'.txt',$contents);
    $i++;
}

编辑

如果您希望在某个字符的某个长度OR后停止,那么您可以使用 stream_get_line() 而不是 fread().它几乎相同,只是它允许您指定任何您希望的结束分隔符.请注意,它将分隔符作为读取的一部分返回.

If you wish to stop after a certain amount of length OR on a certain character, then you could use stream_get_line() instead of fread(). It's almost identical, except it allows you to specify any ending delimiter you wish. Note that it does not return the delimeter as part of the read.

$contents = stream_get_line($fp,1000,".");

这篇关于在 PHP 中拆分文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆