gpt4 book ai didi

PHP - 如果文件存在,则将数据写入新文件,并在 foreach 循环中调用生成文件的每一行

转载 作者:搜寻专家 更新时间:2023-10-31 20:40:00 24 4
gpt4 key购买 nike

我有一段PHP代码如下:

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

以上代码在每次执行时都会将 URL 写入 links/WriteURLs.txt,因此 WriteURLs.txt 文件无法保存结果之前的执行。

问题是我想检查 links/WriteURLs.txt 是否存在,然后开始将 URLs 写入新文件,例如 links/01- WriteURLs.txt, links/02-WriteURLs.txt, ...之后我想开始从生成的文件中读取 URL(即不是所有文件,只有最后一步生成的文件)links/WriteURLs.txt, links/01- WriteURLs.txtlinks/02-WriteURLs.txt 或 ...,并为每个 URL 回显 HELLO WORLD。您可以在下面看到我尝试开发的代码的不完整版本。你能帮我解决这个问题吗?谢谢

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

最佳答案

如果你想从你刚写完的文本文件中读取数据,你可以简单地记录你正在使用的文件的名称,然后在读取过程中使用它,就像这样:

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

关于PHP - 如果文件存在,则将数据写入新文件,并在 foreach 循环中调用生成文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24637200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com