如果文件中不存在字符串,则为fwrite

时间:2016-10-31 17:17:13

标签: php

我目前正在使用自动内容生成器脚本的站点地图。我知道谷歌接受简单文本文件中的站点地图,每行包含一个URL。

所以我创建了一个名为1.txt的文件,并编写了一个脚本,以便在用户访问时将当前页面网址添加到1.txt

test.php是:

$file = 'assets/sitemap/1.txt';
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";
$file = fopen($file, 'a');
fwrite($file, $url);
fclose( $file );

每次有人点击页面时,此脚本会将页面URL写入1.txt。但问题是,它创建了太多的重复链接。所以我想添加一个过滤器,如果它已经存在,则不添加字符串(本例中为URL)。

经过一段时间的冲浪,我得到了一个资源友好的解决方案(第二个片段):PHP check if file contains a string

我进行了以下修改,但它无法正常工作(根本没有添加任何内容):

$file = 'assets/sitemap/1.txt';
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";
if(exec('grep '.escapeshellarg($url).' assets/sitemap/1.txt')) {}
else{
    $file = fopen($file, 'a');
    fwrite($file, $url);
    fclose( $file );
}

1 个答案:

答案 0 :(得分:1)

希望这更容易理解:

$file = 'assets/sitemap/1.txt';
$url  = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";

$text = file_get_contents($file);

if(strpos($text, $url) === false) {
    file_put_contents($file, $url, FILE_APPEND);
}
  • 使用$text
  • 将文件内容读入字符串file_get_contents()
  • 使用$url
  • 检查字符串$text中是否strpos()
  • 如果$url不在字符串$text中,请使用$url
  • file_put_contents()附加到文件中

要计算总行数,您可以开始使用file()将文件行加载到数组中。然后使用$url检查in_array()是否在数组中:

$lines = file($file);
$count = count($lines); // count the lines

if(!in_array($url, $text)) {
    file_put_contents($file, $url, FILE_APPEND);
    $count++; // if added, add 1 to count
}
相关问题