Reputation: 1491
I have a piece of PHP code as follows:
$write_URLs = fopen("links/WriteURLs.txt", "w");
foreach ($list_URLs as $htmlLink) {
GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($write_URLs, $URL ."\n");
}
}
fclose($write_URLs);
Above code writes the URLs on links/WriteURLs.txt
on every execution and so the WriteURLs.txt
file can not save the results of the previous execution.
The problem is that I want to check if links/WriteURLs.txt
exists, then start to write the URLs on a new file, such as links/01-WriteURLs.txt
, links/02-WriteURLs.txt
, ... . After that I want to start reading the URLs from the generated file (i.e. not all files, only the one which is generated in the last step) links/WriteURLs.txt
, links/01-WriteURLs.txt
, links/02-WriteURLs.txt
or ..., and echo the HELLO WORLD
foreach URL
. Below you can see the incomplete version of the code that I tried to develop. Could you please help me how to solve this problem? thanks
$i = 1;
$write_URLs = fopen("links".DIRECTORY_SEPARATOR. $i. "-WriteURLs.txt", "w");
if(file_exists($write_URLs)) {
fclose($write_URLs);
$new_write_URLs = fopen("links".DIRECTORY_SEPARATOR. $i++. "-WriteURLs.txt", "w");
} else {
foreach ($list_URLs as $htmlLink) {
GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($new_write_URLs, $URL ."\n");
}
}
}
fclose($new_write_URLs);
$trimmed = file(???????????, FILE_IGNORE_NEW_LINES);
foreach ($trimmed as $URL) {
echo "Hello World";
}
Upvotes: 2
Views: 109
Reputation: 1689
If you'd like to read the data from the text file you just finished writing, you could simply keep track of the name of the file you are working with and then use it later during the read, like this:
$i = 0;
do {
$filename = "links".DIRECTORY_SEPARATOR . $i++ . "-WriteURLs.txt";
} while (file_exists($filename));
$write_URLs = fopen($filename, "w");
foreach ($list_URLs as $htmlLink) {
$URLs = GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($write_URLs, $URL ."\n");
}
}
fclose($write_URLs);
$trimmed = explode("\n",file_get_contents( $filename ) );
foreach ($trimmed as $URL) {
echo "Hello World";
}
Upvotes: 3