Page 1 of 1

Need help sorting a txt files contents

Posted: Fri Feb 18, 2005 11:52 am
by romeo
I have a text file that has a name type of data on every line then 2 blank lines and then another couple lines of data (not the same number)

so it looks like this:

Name
Street
Address
Phone Fax
Website


Name2
Street2
Address2
Phone Fax2
Website2
comments2


Name3
Street3
Address3
Phone Fax3
Website3



And i want to take that data and make it into a txt file line seperated by a | (not a comma since commas are in the adress fields)


so it would read

Name|Street|Address|Phone Fax|Website
Name2|Street2|Address2|Phone Fax2|Website2|comments2
Name3|Street3|Address3|Phone Fax3|Website3


Any help would be appreciated

Posted: Fri Feb 18, 2005 12:15 pm
by markl999
Maybe something along the lines of:

Code: Select all

<?php
define('INFILE', 'test.txt');
define('OUTFILE', 'test2.txt');
$count = 0;
foreach(file(INFILE) as $line) &#123;
	$line = trim($line);
	if(!empty($line)) &#123;
		$output&#1111;$count]&#1111;] = $line;
	&#125;	else &#123;
		$count++;
	&#125;
&#125;
if(!empty($output)) &#123;
	foreach($output as $line) &#123;
		$newfile&#1111;] = join('|', $line);
	&#125;
&#125;
file_put_contents(OUTFILE, join("\n", $newfile));
?>

Posted: Fri Feb 18, 2005 12:17 pm
by John Cartwright
note: that example requires php5 or above. ( file_put_contents() is php5 only)

Can also look into fopen(), fwrite(), fclose() as a substitute

Posted: Fri Feb 18, 2005 12:19 pm
by markl999
Oh yeah, if you don't have PHP5 just replace:
file_put_contents(OUTFILE, join("\n", $newfile));
with:
$fp = fopen(OUTFILE, 'w');
fputs($fp, join("\n", $newfile));
fclose($fp);

Awesome, Thank you!

Posted: Fri Feb 18, 2005 1:54 pm
by romeo
Awesome, worked right out the box