前置此 PHP 文件

Prepending this PHP File

我有点卡住了,试图用 PHP 为这个文档添加前缀。 请参阅下面的代码本身。

<?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');
}   
?> 

此代码目前适用于写入文件底部,但我想添加到文件顶部。

我实际上是在手动创建 RSS 提要,并且在我的 iOS 应用程序中,它会在读取它们时从上到下对它们进行排序。

如果我对你的理解是正确的,如果你想将内容添加到你的文件的顶部,你需要先获取它的内容;

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

获得内容后,您可以像这样创建新内容;

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

稍后保存文件;

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

稍后替换此行;

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

有了这个;

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