Page 1 of 1

Opening/Converting Text Files

Posted: Mon Jul 27, 2009 1:48 pm
by ugadawg
Hello,

I am fairly new to PHP, and am having some difficulty opening a comma delimited text file and converting the commas to tab delimiters and to output this result in the HTML window. My code, thus far is presented below.

<html>
<?php


$f = file('text.txt');

//Opens file called text.txt and assign the resource ID to fd
$fd = fopen('C:\apache2\Apache2\htdocs\text.txt', 'w+t');


while(list($name, $number, $address) = fgetcsv($fd, 5000, " ")){
//Output the data in HTML format
printf("<p>%s (%s) Tel. %s</p>", $name, $number, $address);
}

fclose($fd);

?>
</html>

Re: Opening/Converting Text Files

Posted: Mon Jul 27, 2009 3:04 pm
by requinix
So is it a CSV file or not?

You're telling fgetcsv that the field delimiter is (what I would guess is) a tab. Don't lie to the function.

Re: Opening/Converting Text Files

Posted: Mon Jul 27, 2009 3:32 pm
by requinix
in a PM, ugadawg wrote:Hello.

No, it's a text file. Not an excel file or anything. The page is simply supposed to take the input text file, and convert the commas to tabs and output to another file.

So, should I use str_replace instead? I have tried both, and just can't seem to figure this application out.
Okay. What your code is doing is opening that text.txt file, treating it as if it had tab-separated values, then writing some of them out to the browser in HTML format.

If the input file has comma-separated values then you shouldn't be telling fgetcsv to use tabs. The default is commas anyways so you can simply forget the third argument.

Once that's working and outputting everything correctly, use fopen, fputcsv (now is when you tell it to use tabs), and fclose, much like how you did to read the original file.

Re: Opening/Converting Text Files

Posted: Mon Jul 27, 2009 5:26 pm
by ugadawg
So, I need to create an array, open the text file, and for each line split into tab delimited lines?
After changing the code, this is what I have thus far...However, it still isn't outputting the converted file..?

$list = array
(
"John Waters, 404.555.4473, 175 Grimley Way",
"Teo Macist, 561.342.3296,175 Habersham Way",
"Johnny Ramone, 324.613.3231, 234 Rockers Lane",
"Axel Rose, 345.533.2345, 431 Obnoxious Road",
);

$fd = fopen('C:\apache2\Apache2\htdocs\text.txt', 'w');

foreach ($list as $line)
{
fputcsv($fd,split("\t",$line));
echo $fd;
}


fclose($fd);

Re: Opening/Converting Text Files

Posted: Mon Jul 27, 2009 6:36 pm
by requinix
...

Look.

Code: Select all

$lines = array();
 
// read in everything
$in = fopen("text.txt", "rt");
while ($line = fgetcsv($in)) {
    $lines[] = $line;
    // here is where you DISPLAY the $line array however you want
}
fclose($in);
 
// write everything back out
$out = fopen("text.txt", "wt");
foreach ($lines as $line) fputcsv($out, $line, "\t");
fclose($out);