0

I am pretty new to PHP and altho I am ratehr good with linux and shell I was wondering if there is an easier different and maybe more efficient way of doing what I would like to do with a PHP script ?

I know how to cat and sort text and contents of a file in shell / linux but was wondering is there a way to do so in PHP ?

Example

if I have a text file that has the contents

hello
hello
hello
Night
Night
Night
Daytime
Daytime
Daytime
clock
clock
clock

ETC ETC ETC how would I read and then create a new file with only one copy of each in the file

hello
Night
Daytime
clock

ETC ETC ...

Please let me know and also if possible can someone direct me to a site that I may learn more about this in PHP

Thanks

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by as.bhanuprakash
0

If you want the duplicates to be ignored, here is your code, where "file.txt" is the text file that holds the contents you specified.

// open the file
$file_handle = fopen("file.txt", "rb");

//while the file is open
while (!feof($file_handle) ) {
	
	//get a line of text
	$line_of_text = fgets($file_handle);
	
	//trim any white space from the line 
	$line_of_text = trim($line_of_text);

	//create a filename with the text on the line
	$line_of_text = $line_of_text.".txt";

	//if the filename doesn't exist...
	if (!file_exists($filename)) {
		
		//create a file with the filename
		$handle = fopen($line_of_text, 'w') or die("can't open file");

		//close the newly created file
		fclose($handle);	
	}

	//repeat all of the above until the end of the file has been reached
}

//close the original text file.
fclose($file_handle);

Edited by J_Search: n/a

0
<?php
// oldfile.txt will have the contents from where you need to copy
// newfilt.txt is the new file we create to have data without duplicates
$old_file_handler = fopen("oldfile.txt", "r");
$new_file_handler_write = fopen("newfile.txt", 'a');

while (!feof($old_file_handler) ) {
	// get the line by line data from the oldfile.txt.
	$old_file_data = fgets($old_file_handler);
	// Check if that line or data is already present in the newfile.txt
	$data_found = false;
	$new_file_handler_read = fopen("newfile.txt", "r");
	while (!feof($new_file_handler_read) ) {
		$new_file_data = fgets( $new_file_handler_read );
		if (trim($old_file_data)  == trim($new_file_data) ) {
			$data_found = true;
			break;
		}
	}
	// Write the data in the new file only if that data is not present in the newfile.txt
	if ( $data_found == false ) {
		fwrite($new_file_handler_write,$old_file_data);
	}
}


?>

The above code works fine. check it out.

Also to learn php ,i would recommend
http://php.net/
http://w3schools.com/php/default.asp

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.