tags:

views:

36

answers:

2

Hello, 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 text file should be empty.

How can I achieve this?

Thanks, Rafael

+2  A: 

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.

kijin
Ah yes that was my plan B. Thanks!
RafaelM
A: 

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', '');
meagar
No, I need to actually remove the URL from the urls.txt files after it is processed by function1()
RafaelM
My solution will work then, if you simply wrap it in a while loop, but it's doing exactly what kijin suggested: Rewriting the entire file each time.
meagar