Heim  >  Fragen und Antworten  >  Hauptteil

Erstellen Sie eine CSV-Datei mit einer großen Anzahl von TXT-Dateien

Ich versuche, eine große TXT-Datei zu lesen und die erste Zeile als Kopfzeile und den Rest des Textes als Inhalt zu speichern und dann in eine CSV-Datei zu exportieren.

Ich erstelle eine ID für eine CSV-Datei, die durch Iteration erhöht wird, aber wenn ich eine Fehlermeldung erhalte, die ich in der Iteration nicht sehen kann, weil beim Speichern des Inhalts im Array der letzte Inhalt zum Wert hinzugefügt wird.

Ich muss eine CSV mit 3 „Spalten“ mit den Namen „id“, „titulo“ und „contentido“ erstellen und die Informationen in einem Array pro Datei speichern. Eine TXT-Datei, eine Array-Iteration.

Entschuldigung für mein schlechtes Englisch.

Das ist mein 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;

Beispiel einer Datei zum Lesen.

Datei 1.txt

Titulo 1
texto 1

Datei 2.txt

Titulo 2
texto 2

CSV

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

Vielen Dank, Freunde.

P粉287254588P粉287254588210 Tage vor327

Antworte allen(2)Ich werde antworten

  • P粉198670603

    P粉1986706032024-02-27 11:15:53

    我使用这个形式是因为我可以更好地格式化我的答案。

    我需要文件的全部内容减去第一行都在 $contenido 列中。

    现在,使用您的代码可以正常工作,但如果同一文件在内容后有多于一行,它将使用每一行作为结果的新行。

    例如我现在使用这个文件

    文件1.txt

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

    文件2.txt

    Titulo 2
    texto 2, texto 2, texto 2, texto 2, texto 2, texto 2
    
    Some text 2 of the same archive

    这会生成这个 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"

    但我需要这个:

    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"

    内容保存 txt 文件中的所有空格和 \n 非常重要,因为该 txt 文件是博客的帖子。

    一个文件.txt 的示例

    ¿Como puedo comer galletas?<-- Title
    
    Las galletas se comen con la boca, poco a poco masticando.
    
    

    ¿Cuántos sabores de galletas hay?

    Pues hay de todos los que puedas imaginar.

    标题后的所有文本都必须保持在同一行,以保存 \n 和所有内容。

    一个文件在 CSV 中只有一行。

    非常感谢你,我对我的英语感到抱歉。

    Antwort
    0
  • P粉548512637

    P粉5485126372024-02-27 11:12:31

    第 19 行的 $contenido 未定义,它试图将一个不存在的变量与 .= 连接起来。 $contenido 变量也不是必需的,因为每个存档行都在 $datosparacsv 中定义。

    也无需定义 $delimitador$enclosure,因为定义的值也是默认值。

    这是正确的 PHP 代码,其中包含预期的 CSV 输出以及解释每个修改行的注释。

    它还根据需要保留内容中的新行和空格。

    文件/1.txt

    Titulo 1
    texto 1

    文件/2.txt

    Titulo 2
    texto 2
    
    texto3
    
    
    
    texto4

    这将使用此数据保存 entradas.csv。

    ID,titulo,contenido
    0,"Titulo 1","texto 1"
    1,"Titulo 2","texto 2
    
    texto3
    
    
    
    texto4"

    Antwort
    0
  • StornierenAntwort