Need help sorting a txt files contents

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
romeo
Forum Contributor
Posts: 138
Joined: Sun Apr 21, 2002 12:50 pm

Need help sorting a txt files contents

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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));
?>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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);
romeo
Forum Contributor
Posts: 138
Joined: Sun Apr 21, 2002 12:50 pm

Awesome, Thank you!

Post by romeo »

Awesome, worked right out the box
Post Reply