Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving file pointer up one line (php)?

Tags:

php

file-io

I am attempting to automate the sitemap.xml file on my site since the content is constantly changing. I currently open the file for appending: fopen($file_name, 'a'); so that I can add the new set of tags. However, I just noticed that the entire sitemap file has to be ended with a tag which means that every time I open the file, I need to append the text not to the end of the file, but to 1 line from the end.

So basically, how can I move the file pointer up after opening the file for appending so that I can achieve this? Thanks.

Update: here is what the sitemap looks like:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">
    <url>
        <loc>...</loc>
        <lastmod>2009-08-23</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    </urlset>

so whenever I append, i need to add the <url>..</url> part which must go right before the closing </urlset> tag. I already have code that can append the xml to the end of the file. I just need to figure out how to append the new portion right before the closing tag.


1 Answers

Use php fseek() to seek to the end of the file (find using filesize()), then iterate backwards one line. read the last line and store it temporarily. overwrite the last line with what you want to insert, then append the temporary line you stored previously.

To iterate backwards one line, use fseek combined with fgetc()

$offset = filesize($fhandle) - 1;
fseek($fhandle, $offset--); //seek to the end of the line
while(fgetc($fhandle) != '\n') {
   fseek($fhandle, $offset--);
}

and now your internal file pointer should be pointed to a line before the last line. off course you'll have to deal with corner cases when your file only has one line, but I'll let you figure out the details ;)

now store the last line in a tmp variable

$lastline = fgets($fhandle);
fseek($fhandle, $offset); //go back to where the last line began

insert your line, and append the last line at the end of the file

fwrite($fhandle, $myLine);
fwrite($fhandle, $lastline);
like image 105
Charles Ma Avatar answered Sep 25 '26 13:09

Charles Ma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!