开发者

Read a line from a text file, then delete it

I have a text file , filled with pipe separated URLs, like this:

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

etc.

I currently have this code to read each url from the file and pass it to a function:

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

  foreach ($urlarray as $url) {

   function1($url);

   }

?>   

What I want to do next is, after function1() is done, delete that URL from the text file.That way, when the script is done going through all the URLs in urls.txt, this t开发者_StackOverflow社区ext file should be empty.

How can I achieve this?

Thanks, Rafael


There's no way to delete stuff from the beginning or middle of a text file without rewriting the whole thing. See here. Just go through all the URLs and then delete the file, or implode() any remaining URLs and overwrite the original file with it.


$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);
}


You could pull the first URL of the exploded list, implode it 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);
}

Are you expecting this process to be interrupted? If not, it makes more sense to simply assume that all the URLs will be processed, and blank the file when the program is complete:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜