fwrite if string doesn't exist in file

后端 未结 1 391
梦毁少年i
梦毁少年i 2021-01-27 12:51

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 cre

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 13:03

    This is hopefully easier to understand:

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

    0 讨论(0)
提交回复
热议问题