Providing this PHP file

I am a bit stuck trying to add this document to 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 at the bottom of the file, but I would like to add it at the beginning.

I am essentially creating an RSS feed by hand and with my iOS app, it sorts them from top to bottom as it reads them.

+3


source to share


1 answer


If I understood you correctly and if you want to add content to the beginning of your file, you need to get it first,

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

      

Once you have the content, 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;

      

Save the file later;



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

      

Replace this line shortly;

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

      

+1


source







All Articles