Home > front end >  Create a csv file with a lot of txt files
Create a csv file with a lot of txt files

Time:08-02

i'm trying to read a lot of txt files and save the first line as a title, and the rest of text as a content, then export to a CSV file.

i create a id for CSV that increase by iteration, but when i have an error that i cant see in the iteration because when it save the content in the array add the last content to this value.

I need to create a CSV with 3 "columns" named, id, titulo and contenido and by each file, save in a array the information. One txt file, one iteration of array.

Sorry for my english.

this is my code:

<?php
/* Cogemos todos los archivos txt de la carpeta archivos del servidor */
$files = glob("archivos/*.txt");
/* Creamos el array para guardar los datos y le metemos la primera línea que es el nombre de los campos a importar */
$datosparacsv=array(array("ID","titulo","contenido"));
/* Creamos el id que tendrá cada campo del array para después poder importar */
$id = 0;
/* Recorremos cada archivo para coger los datos */
foreach($files as $file) {
    /* Sacamos el título de la primera línea del archivo txt */
    $titulo = trim(fgets(fopen($file, 'r')));
    /* Sacamos el resto del contenido pero quitamos la primera linea con el condicional if*/
    $archivo = file($file);
    foreach ($archivo as $num=>$line){
        if ($num==0) {
            continue;
        }
        else{
            $contenido .= $line."\n";
        }
    }
    /* Añadimos el contenido extraido al array para luego pasarlo a CSV */
    array_push($datosparacsv, array($id,$titulo,$contenido));
    /* Sumamos uno al id para que sea único */
    $id  ;
}
$delimitador = ','; //parameter for fputcsv
$enclosure = '"'; //parameter for fputcsv
//convert array to csv
$archivocsv = fopen('entradas.csv', 'w ');
foreach ($datosparacsv as $data_line) {
    fputcsv($archivocsv, $data_line, $delimitador, $enclosure);
}

$data_read="";
rewind($archivocsv);
//read CSV
while (!feof($archivocsv)) {
    $data_read .= fread($archivocsv, 8192); // will return a string of all data separeted by commas.
}
fclose($archivocsv);
echo $data_read;

Example of files to read.

File 1.txt

Titulo 1
texto 1

File 2.txt

Titulo 2
texto 2

CSV

id, titulo, contenido, 0, Titulo 1, texto 1, 1, Titulo 2, texto 2

Thank you very much mates.

CodePudding user response:

$contenido on line 19 is undefined and it's trying to concatenate a non-existent variable with .=. The $contenido variable also isn't required because each archive line is defined in $datosparacsv.

It's also unnecessary to define $delimitador and $enclosure because the defined values are also the default values.

Here's the correct PHP code with the expected CSV output with comments explaining each modified line.

<?php
    /* Cogemos todos los archivos txt de la carpeta archivos del servidor */
    $files = glob("archivos/*.txt");

    /* Creamos el array para guardar los datos y le metemos la primera línea que es el nombre de los campos a importar */
    $datosparacsv = array(
        array(
            "ID",
            "titulo",
            "contenido"
        )
    );

    /* Creamos el id que tendrá cada campo del array para después poder importar */
    $id = 0;

    foreach($files as $file) {
        /* Sacamos el resto del contenido pero quitamos la primera linea con el condicional if*/
        $archivos = file($file);

        // Remove and retrieve CSV heading values from each file with array_shift instead of a conditional in each $archivo iteration
        $titulo = trim(array_shift($archivos));

        foreach ($archivos as $archivo) {
            // Append to the array with $datosparacsv[] instead of array_push() while incrementing $id
            $datosparacsv[] = array(
                $id  ,
                $titulo,
                trim($archivo)
            );
        }
    }

    //convert array to csv
    $archivocsv = fopen('entradas.csv', 'w ');

    foreach ($datosparacsv as $data_line) {
        // Add the data to the CSV with the default delimiter and enclosure
        fputcsv($archivocsv, $data_line);
    }

archivos/1.txt

Titulo 1
texto 1

archivos/2.txt

Titulo 2
texto 2
texto 3
texto 4

This saves entradas.csv with this data.

ID,titulo,contenido
0,"Titulo 1","texto 1"
1,"Titulo 2","texto 2"
2,"Titulo 2","texto 3"
3,"Titulo 2","texto 4"

CodePudding user response:

i use this forme because i can format my anser better.

i need that the whole content of the file less the first line was in the column $contenido.

Now, with your code, works fine but if the same file has more than one line after content, it uses each line as a new line of the result.

For example i use now this files

Archivo 1.txt

Titulo 1
texto 1,texto 1

Some more text in file 1

Archivo 2.txt

Titulo 2
texto 2, texto 2, texto 2, texto 2, texto 2, texto 2

Some text 2 of the same archive

and this generates this entradas.csv

ID,titulo,contenido
0,"Titulo 1","texto 1,texto 1"
1,"Titulo 1",
2,"Titulo 1","Some more text in file 1"
3,"Titulo 2","texto 2, texto 2, texto 2, texto 2, texto 2, texto 2"
4,"Titulo 2",
5,"Titulo 2","Some text 2 of the same archive"

But i need that:

ID,titulo,contenido
0,"Titulo 1","texto 1,texto 1

Some more text in file 1"
1,"Titulo 2","texto 2, texto 2, texto 2, texto 2, texto 2, texto 2

Some text 2 of the same archive"

It's important that the contents saves all spaces and \n that they have in the txt file because this txt files are posts of a blog.

An example of one file.txt

¿Como puedo comer galletas?<-- Title

Las galletas se comen con la boca, poco a poco masticando.

<h2>¿Cuántos sabores de galletas hay?</h2>

Pues hay de todos los que puedas imaginar.

and all of this text after title have to stay in the same line saving \n and all.

One file only one line in the CSV.

thank you very much and im sorry for my english.

  • Related