Mohammad Salehi
Mohammad Salehi

Reputation: 776

remove empty line after edit file in php

I'm creating a text sitemap for my site it looks like this:

sitemap.txt:

https://example.com/
https://example.com/estate/showAll
https://example.com/estate/search
https://example.com/site/about
https://example.com/site/contact
https://example.com/post/show/41
https://example.com/post/show/42
https://example.com/post/show/43

when the user delete post 42 my sitemap should change to:

https://example.com/
https://example.com/estate/showAll
https://example.com/estate/search
https://example.com/site/about
https://example.com/site/contact
https://example.com/post/show/41
https://example.com/post/show/43

I tried these ways but they didn't work as expected:

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/post/show/42';
$sitmap =str_replace($line, '', $sitmap);
file_put_contents('sitemap.txt', $sitmap);

this code shows an empty line in sitemap.txt

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/post/show/42';
$sitmap =str_replace($line, '', $sitmap);
$sitmap =str_replace($line, chr(8), $sitmap);
file_put_contents('sitemap.txt', $sitmap);

chr(8) shows backspace character BS it doesn't remove empty newline.

I have done it with below code, but I think it uses too much memory if sitemap.txt gets large

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/posst/show/'. $id;
$sitmap = explode(PHP_EOL, $sitmap);

if ($key = array_search($line, $sitmap)) {
     unset($sitmap[$key]);
}
$sitmap = implode(PHP_EOL, $sitmap);

file_put_contents('sitemap.txt', $sitmap);

Is there a better way?

Upvotes: 0

Views: 88

Answers (1)

Syscall
Syscall

Reputation: 19778

You could just replace the line + newline character (\n) :

$line = 'https://example.com/post/show/'. $id;
$file = 'sitemap.txt';
file_put_contents($file, 
    str_replace("$line\n", '', file_get_contents($file))
);

As pointed by Nigel Ren (see comment below), "$line\n" should maybe replaced by $line.PHP_EOL.

This depends of how you're building your file.

Upvotes: 3

Related Questions