Page 1 of 1

write array values to file

Posted: Thu Jul 22, 2010 7:17 pm
by joshmmo
Hello,

Im trying to do a simple task of reading a csv file which i can do fine, and i read it to an array and i want to assign each value for to a variable and write it out to a text file in the order i need.

This is what i have so far.

Code: Select all

$file_handle = fopen("test.csv", "r");
while (!feof($file_handle) ) {

$line_of_text = fgetcsv($file_handle, 10240);

$lines = implode("<BR>",$line_of_text);

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $lines);
fclose($fh);

print $lines;
}
Notice I print out $lines just fine! But i cannot write $lines to a file? The file gets created however it is empty. Whats wrong?
Thanks for the help!

Also one other thing, I cannot save $lines_of_text[1] to a file either. Nothing gets written in the txt file :(

Re: write array values to file

Posted: Thu Jul 22, 2010 10:55 pm
by AbraCadaver
Assuming all permissions are right, what happens if you do this:

Code: Select all

$file_handle = fopen("test.csv", "r") or die("can't open file");
$fh = fopen("testFile.txt", 'w') or die("can't open file");

while (!feof($file_handle) ) {
   $line_of_text = fgetcsv($file_handle, 10240);
   $lines = implode("<BR>",$line_of_text);
   fwrite($fh, $lines);
   print $lines;
}

Re: write array values to file

Posted: Mon Jul 26, 2010 4:18 pm
by joshmmo
interesting, that worked, thankyou, now ill just edit it according to what i need.

What was the problem? Im not sure I still understand what it was.

Re: write array values to file

Posted: Mon Jul 26, 2010 4:24 pm
by joshmmo
Errr one last question, how can I print specific values or the array?

For example

Code: Select all

$lines = implode("<BR>",$line_of_text[1]);
   fwrite($fh, $lines);

That doesnt write those values of the array to the text file. It dies on the implode.

Re: write array values to file

Posted: Mon Jul 26, 2010 4:39 pm
by AbraCadaver
That's because implode is creating a string from array values. If you just want to write one line, don't implode():

Code: Select all

fwrite($fh, $line_of_text[1]);

Re: write array values to file

Posted: Mon Jul 26, 2010 5:22 pm
by joshmmo
amazing ;) thanks so much, gg implode, i guess i need to read up on that one. Thanks again!!