user3050153
user3050153

Reputation: 19

Trying to save each array to a txt file using php

<?php
$file = fopen("test2.csv","r");

while(! feof($file)) {
    print_r(fgetcsv($file));
    $textfilename=[0].".txt";
    file_put_contents ([1]);
}

fclose($file);

?> 

This will take data like

Array ( 
    [0] => name 
    [1] => download information 
) 
Array ( 
    [0] => Sense and Sensibility Instant Digital Download 
    [1] => Please visit the following link to download your digital product: http://archive.org/download/0_sense_and_sensibility_librivox/Sense_Sensibility_1107_64kb_mp3.zip 
) 

and for each 0 => make that the file name. Then store [1] into the file and save it. But i'm running into an error.

Upvotes: 0

Views: 128

Answers (2)

dev
dev

Reputation: 990

if (($handle = fopen("test2.csv", "r")) !== FALSE) 
{
    while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
        $textfile = $line[0] . ".txt";
        file_put_contents($textfile, $line[1]);
    }
    fclose($handle);
}

This code;

  1. Makes sure you can open & read the csv file
  2. For each line in the csv file
  3. Gets the line, and creates a new text file whose name is the first element in the line array (ie. the first column in the csv file for that line)
  4. Puts the second column from the csv file into the new text file
  5. Closes the file

Does that make sense?

Upvotes: 0

Christian D.
Christian D.

Reputation: 65

You mean something like this? Not tested yet.

<?php
$file = fopen("test2.csv","r");

while(($line = fgetcsv($handle, 1000, ",")) !== FALSE)
  {
  $textfilename=$line[0].".txt";
  file_put_contents($textfilename, $line[1]);
  }

fclose($file);

?> 

Upvotes: 1

Related Questions