Read a line from a text file, then delete it

I have a text file filled with URLs separated by feeds, for example:

http://www.example.com|http://www.example2.com|http://www.example3.com|.... 

and etc.

Currently, this code reads each URL from a file and passes it to the functions:

<?php
  $urlarray = explode("|", file_get_contents('urls.txt'));

  foreach ($urlarray as $url) {

   function1($url);

   }

?>   

What I want to do next, after completing function 1 (), remove this URL from the text file. Thus, when the script runs through all the URLs in urls.txt, this text file should be empty.

How can i achieve this?

Thanks Raphael

+3
source share
3 answers

, . . . URL-, implode() URL- .

+3
$urlarray = explode("|", $contents = file_get_contents('urls.txt'));
print_r($contents);
foreach ($urlarray as $url) {
   $tempcontent = str_replace($url . "|", " ", $contents, $x = 1);
    $contents = $tempcontent;
   $fp = fopen('urls.txt', "w");
   fwrite($fp, $contents);
   fclose($fp);
}
+2

You can pull out the first URL of the exploded list, blow it up and write it back to the file:

while($urls = explode('|', file_get_contents('urls.txt'))) {

  $first_url = array_shift($urls);

  file_put_contents('urls.txt', implode('|', $urls));

  function1($first_url);
}

Do you expect this process to be interrupted? If not, it makes sense to simply assume that all URLs will be processed, and an empty file when the program is completed:

foreach (explode('|', file_get_contents('urls.txt') as $url) {
  function1($url);
}

file_put_contents('urls.txt', '');
0
source

Source: https://habr.com/ru/post/1772224/


All Articles