douxuan1284 2016-10-31 17:17
浏览 62
已采纳

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

I am currently working an auto-content-generator script's sitemap. I got to know that google accept sitemap in simple text file that contains one URL per line.

so I created a file named 1.txt and wrote a script to add current page URL to 1.txt when a user visits.

test.php is:

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

This script writes the page URLto 1.txt every time someone hits the page. But the problem is, it creates too much duplicate links. So I want to add a filter to not add a string (URL in this case) if it already exists.

After surfing a while, I got a solution here (second snippet) that is resource friendly: PHP check if file contains a string

I made the following modification but it is not working (not adding anything at all):

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

1条回答 默认 最新

  • doutao4480 2016-10-31 17:24
    关注

    This is hopefully easier to understand:

    $file = 'assets/sitemap/1.txt';
    $url  = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."
    ";
    
    $text = file_get_contents($file);
    
    if(strpos($text, $url) === false) {
        file_put_contents($file, $url, FILE_APPEND);
    }
    
    • Read the file contents into a string $text using file_get_contents()
    • Check if $url is in the string $text using strpos()
    • If $url is not in the string $text, append the $url to the file using file_put_contents()

    To count the total lines, you can start using file() to load the file lines into an array. Then check if the $url is in the array using 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改