Pregunta

¿Cómo puedo dividir un archivo de texto grande en archivos separados según el número de caracteres usando PHP?Por lo tanto, un archivo de 10.000 caracteres dividido cada 1.000 caracteres se dividiría en 10 archivos.Además, ¿puedo dividir sólo después de encontrar un punto?

Gracias.

ACTUALIZACIÓN 1:Me gusta el código de Zombats, eliminé algunos errores y se me ocurrió lo siguiente, pero ¿alguien sabe cómo dividir solo después de un punto?

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

ACTUALIZACIÓN 2:Tomé la sugerencia de Zombats y modifiqué el código a continuación y parece funcionar:

$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++;
    }
¿Fue útil?

Solución

Usted debe ser capaz de lograr esto fácilmente con un fread () básica. Puede especificar el número de bytes que desea leer, por lo que es trivial para leer en una cantidad exacta y la enviará en un nuevo archivo.

Trate algo como esto:

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

Editar

Si desea parar después de una cierta cantidad de longitud o en un cierto carácter, entonces usted podría utilizar stream_get_line () en lugar de fread(). Es casi idéntica, excepto que le permite especificar cualquier delimitador final que desea. Tenga en cuenta que lo hace no devolver el delimitador como parte de la lectura.

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

Otros consejos

Hay un error en la función de ejecución; $split variable no definida.

La forma más fácil es leer el contenido del archivo, dividir el contenido, a continuación, guarde a otros dos archivos. Si los archivos son más que unos pocos gigabytes, que va a tener un problema de hacerlo en PHP, debido a las limitaciones de tamaño del número entero.

También puede escribir una clase para hacer esto para usted.

<?php

/**
* filesplit class : Split big text files in multiple files
*
* @package
* @author Ben Yacoub Hatem <hatem@php.net>
* @copyright Copyright (c) 2004
* @version $Id$ - 29/05/2004 09:02:10 - filesplit.class.php
* @access public
**/
class filesplit{
    /**
     * Constructor
     * @access protected
     */
    function filesplit(){

    }

    /**
     * File to split
     * @access private
     * @var string
     **/
    var $_source = 'logs.txt';

    /**
     *
     * @access public
     * @return string
     **/
    function Getsource(){
        return $this->_source;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setsource($newValue){
        $this->_source = $newValue;
    }

    /**
     * how much lines per file
     * @access private
     * @var integer
     **/
    var $_lines = 1000;

    /**
     *
     * @access public
     * @return integer
     **/
    function Getlines(){
        return $this->_lines;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setlines($newValue){
        $this->_lines = $newValue;
    }

    /**
     * Folder to create splitted files with trail slash at end
     * @access private
     * @var string
     **/
    var $_path = 'logs/';

    /**
     *
     * @access public
     * @return string
     **/
    function Getpath(){
        return $this->_path;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setpath($newValue){
        $this->_path = $newValue;
    }

    /**
     * Configure the class
     * @access public
     * @return void
     **/
    function configure($source = "",$path = "",$lines = ""){
        if ($source != "") {
            $this->Setsource($source);
        }
        if ($path!="") {
            $this->Setpath($path);
        }
        if ($lines!="") {
            $this->Setlines($lines);
        }
    }


    /**
     *
     * @access public
     * @return void
     **/
    function run(){
        $i=0;
        $j=1;
        $date = date("m-d-y");
        unset($buffer);

        $handle = @fopen ($this->Getsource(), "r");
        while (!feof ($handle)) {
          $buffer .= @fgets($handle, 4096);
          $i++;
              if ($i >= $split) {
              $fname = $this->Getpath()."part.$date.$j.txt";
               if (!$fhandle = @fopen($fname, 'w')) {
                    print "Cannot open file ($fname)";
                    exit;
               }

               if (!@fwrite($fhandle, $buffer)) {
                   print "Cannot write to file ($fname)";
                   exit;
               }
               fclose($fhandle);
               $j++;
               unset($buffer,$i);
                }
        }
        fclose ($handle);
    }


}
?>


Usage Example
<?php
/**
* Sample usage of the filesplit class
*
* @package filesplit
* @author Ben Yacoub Hatem <hatem@php.net>
* @copyright Copyright (c) 2004
* @version $Id$ - 29/05/2004 09:14:06 - usage.php
* @access public
**/

require_once("filesplit.class.php");

$s = new filesplit;

/*
$s->Setsource("logs.txt");
$s->Setpath("logs/");
$s->Setlines(100); //number of lines that each new file will have after the split.
*/

$s->configure("logs.txt", "logs/", 2000);
$s->run();
?>

http://www.weberdev.com/get_example-3894.html

tuve clase de punto fijo y trabajo perfecto con el archivo .txt.

<?php

/**
* filesplit class : Split big text files in multiple files
*
* @package
* @author Ben Yacoub Hatem <hatem@php.net>
* @copyright Copyright (c) 2004
* @version $Id$ - 29/05/2004 09:02:10 - filesplit.class.php
* @access public
**/
class filesplit{
    /**
     * Constructor
     * @access protected
     */
    function filesplit(){

    }

    /**
     * File to split
     * @access private
     * @var string
     **/
    var $_source = 'logs.txt';

    /**
     *
     * @access public
     * @return string
     **/
    function Getsource(){
        return $this->_source;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setsource($newValue){
        $this->_source = $newValue;
    }

    /**
     * how much lines per file
     * @access private
     * @var integer
     **/
    var $_lines = 1000;

    /**
     *
     * @access public
     * @return integer
     **/
    function Getlines(){
        return $this->_lines;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setlines($newValue){
        $this->_lines = $newValue;
    }

    /**
     * Folder to create splitted files with trail slash at end
     * @access private
     * @var string
     **/
    var $_path = 'logs/';

    /**
     *
     * @access public
     * @return string
     **/
    function Getpath(){
        return $this->_path;
    }

    /**
     *
     * @access public
     * @return void
     **/
    function Setpath($newValue){
        $this->_path = $newValue;
    }

    /**
     * Configure the class
     * @access public
     * @return void
     **/
    function configure($source = "",$path = "",$lines = ""){
        if ($source != "") {
            $this->Setsource($source);
        }
        if ($path!="") {
            $this->Setpath($path);
        }
        if ($lines!="") {
            $this->Setlines($lines);
        }
    }


    /**
     *
     * @access public
     * @return void
     **/
    function run(){

        $buffer = '';
        $i=0;
        $j=1;
        $date = date("m-d-y");
        $handle = @fopen ($this->Getsource(), "r");

        while (!feof ($handle)) {

            $buffer .= @fgets($handle, 4096);
            $i++;

            if ($i >= $this->getLines()) { 

                // set your filename pattern here.
                $fname = $this->Getpath()."split_{$j}.txt";

                if (!$fhandle = @fopen($fname, 'w')) {
                    print "Cannot open file ($fname)";
                    exit;
                }

                if (!@fwrite($fhandle, $buffer)) {
                    print "Cannot write to file ($fname)";
                    exit;
                }
                fclose($fhandle);
                $j++;
                unset($buffer,$i);
            }
        } 
        if ( !empty($buffer) && !empty($i) ) {
            $fname = $this->Getpath()."split_{$j}.txt";

            if (!$fhandle = @fopen($fname, 'w')) {
                print "Cannot open file ($fname)";
                exit;
            }

            if (!@fwrite($fhandle, $buffer)) {
                print "Cannot write to file ($fname)";
                exit;
            }
                fclose($fhandle);
            unset($buffer,$i);  
        }
        fclose ($handle);
    }


}
?>

Uso Ejemplo

<?php

require_once("filesplit.class.php");

$s = new filesplit;
$s->Setsource("logs.txt");
$s->Setpath("logs/");
$s->Setlines(100); //number of lines that each new file will have after the split.
//$s->configure("logs.txt", "logs/", 2000);
$s->run();
?>

En la función de ejecución, hice los siguientes ajustes, para fijar la "división no se define" advertencia.

function run(){

        $buffer='';
        $i=0;
        $j=1;
        $date = date("m-d-y");
        $handle = @fopen ($this->Getsource(), "r");

        while (!feof ($handle)) {

            $buffer .= @fgets($handle, 4096);
            $i++;

            if ($i >= $this->getLines()) { // $split was here, empty value..

                // set your filename pattern here.
                $fname = $this->Getpath()."dma_map_$date.$j.csv";

                if (!$fhandle = @fopen($fname, 'w')) {
                    print "Cannot open file ($fname)";
                    exit;
                }

                if (!@fwrite($fhandle, $buffer)) {
                    print "Cannot write to file ($fname)";
                    exit;
                }
                fclose($fhandle);
                $j++;
                unset($buffer,$i);
            }
        }
        fclose ($handle);
    }

He utilizado esta clase para dividir una línea de 500.000 archivo CSV en 10 archivos, por lo phpmyadmin pueden consumir sin problemas de tiempo de espera. Trabajado como un encanto.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top