John Davidson

php - Create a csv file with a lot of txt files

0 comments
Message:


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.



My Answer:
columns: ID, Title, Content

Here is a sample code to achieve this:

php
$csvFile = fopen('output.csv', 'w');
fputcsv($csvFile, array('ID', 'Title', 'Content'));

$id = 1;

foreach (glob('*.txt') as $filename) {
$lines = file($filename);
$title = trim($lines[0]);
$content = trim(implode("\n", array_slice($lines, 1)));

fputcsv($csvFile, array($id, $title, $content));

$id++;
}

fclose($csvFile);


This code will read all the .txt files in the current directory, extract the first line as the title and the rest as content, and then write them to a CSV file with the ID, Title, and Content columns. Each row in the CSV file will have a unique ID starting from 1.

Rate this post

3 of 5 based on 6350 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us