Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending this PHP File

Tags:

php

rss

prepend

I'm a little stuck attempting to prepend this document with PHP. Please see below for the code itself.

<?php

if(isset($_POST['inputTitle']) && isset($_POST['inputDate']) && isset($_POST['inputLink'])) {
      $data = "<item>" . "\r\n" . "<title>" . $_POST['inputTitle'] . "</title>" . "\r\n" . "<description>" . $_POST['inputDate'] . "</description>" . "\r\n" . "<link>" . $_POST['inputLink'] . "</link>" . "\r\n" . "</item>" . "\r\n" . "\r\n";
    $ret = file_put_contents('filename.rss', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "<b>Thank you for adding a news item.</b> <br />";
        echo "If this news item does not appear on the application, please contact IT Support including a screenshot of this webpage. <br />";
        echo "<br />";
        echo "<br />";
        echo "###################### <br />";
        echo "$ret bytes written to file. <br />";
        echo "###################### <br />";

    }
}
else {
   die('no post data to process');
}   
?> 

This code currently works for writing to the bottom of a file, but I'd like to add to the top of it.

I'm essentially creating an RSS feed manually, and with my iOS application it sorts them from top to bottom as it reads them.

like image 987
GlenRitchie Avatar asked Jun 16 '26 22:06

GlenRitchie


1 Answers

If I understood you correctly and if you want to add content to the top of your file, you'd need to get the contents of it first;

$content = file_get_contents("filename.rss");

Once you have the contents you can create new content like this;

$data = "<item>" . "\r\n" . "<title>" . $_POST['inputTitle'] . "</title>" . "\r\n" . "<description>" . $_POST['inputDate'] . "</description>" . "\r\n" . "<link>" . $_POST['inputLink'] . "</link>" . "\r\n" . "</item>" . "\r\n" . "\r\n";

$content = $data.$content;

Later save the file;

$ret = file_put_contents("filename.rss", $data, LOCK_EX);

Shortly replace this line;

$ret = file_put_contents('filename.rss', $data, FILE_APPEND | LOCK_EX);

With this;

$content = file_get_contents("filename.rss");
$ret = file_put_contents("filename.rss", $data.$content, LOCK_EX);
like image 161
Ilgıt Yıldırım Avatar answered Jun 19 '26 11:06

Ilgıt Yıldırım



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!