I want to put the data from a text file and remove something certein from in between, and want to repeat the same

29 Views Asked by At

I have a text file and in that text file there is some data goes like

John || Sekram
JOHN || Doe
Lorem || Ipsum

now my problem is i dont know where to start but i want to put this data in to tow diffrent variables and ignore || and then remove that line everytime i refresh the webpage.

I wrote this php code but it extract the whole line

  $file = "data.txt";
$f = fopen($file, 'r');
$line = fgets($f);
//echo $line;
fclose($f);


$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));

now what my code doing is, it extract the whole line and then erase it. i want this to be store in tow diffrent variable and remove the || in the middle then erase the line.

This data is way too big to perform this manually. Any help will be appriciated.

1

There are 1 best solutions below

0
Adrian Costache On

To extract the data in two separate variables and remove the line every time the page is refreshed, you can use the following PHP code:

$file = "data.txt";
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);

// Extract the data in two separate variables
$data = explode("||", $line);
$name1 = trim($data[0]);
$name2 = trim($data[1]);

// Remove the line from the file
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));

This code reads the first line of the text file using fgets() and then extracts the data in two separate variables using explode() function. The trim() function is used to remove any whitespace around the names.

Then, the code removes the first line from the file using file() function to read the file into an array, array_shift() function to remove the first element (the first line), and file_put_contents() function to write the remaining lines back to the file.

You can use the $name1 and $name2 variables as needed in your PHP script.