簡體   English   中英

嘗試使用PHP修改文件

[英]Trying to modify a file with PHP

函數remove_tags必須進入文件並刪除</channel></rss> 但是,如果不覆蓋整個文件,我似乎無法工作。

<html><body><?php
$file_name = "rss.xml";

if (!file_exists($file_name)) {
        initialize_xml($file_name);
}

remove_tags($file_name);
write_content($file_name);
close_tags($file_name);
finish();

function initialize_xml($name) {
        $rss = fopen($name, 'w+') or die('can\'t open file_init');
        fwrite($rss, "<?xml version=\"1.0\" ?>\n");
        fwrite($rss, "<rss version=\"2.0\">\n");
        fwrite($rss, "<channel>\n");
        fwrite($rss, "<title>CBS IT Update Feed</title>\n");
        fwrite($rss, "<description>This feed will keep users up to date on IT issues that may arise</description>\n");
        fwrite($rss, "<link>http://google.com</link>\n");
        fwrite($rss, "<managingEditor>max.mackie@blood.ca</managingEditor>\n");
        fwrite($rss, "<webMaster>max.mackie@blood.ca</webMaster>\n\n");
        fwrite($rss, "</channel></rss>");
        fclose($rss);
}

function write_content($name) {
        $rss = fopen($name, 'a') or die('can\'t open file_write');
        fwrite($rss, "<item>\n");
        fwrite($rss, "<title>");
        fwrite($rss, $_POST['title']);
        fwrite($rss, "</title>\n");

        fwrite($rss, "<description><![CDATA[");
        fwrite($rss, $_POST['desc']);
        fwrite($rss, "]]></description>\n");

        fwrite($rss, "<date>");
        $today = getdate();
        $timestamp_format = $today['weekday'] . ' ' . $today['month'] . ' ' . $today['mday'] . ' ' . $today['hours'] . ' ' . $today['minutes'] . ' ' . $today['seconds'];
        fwrite($rss, $timestamp_format);
        fwrite($rss, "</date>\n");
        fwrite($rss, "</item>\n\n");
        fclose($rss);
}

function close_tags($name) {
        $rss = fopen($name, 'a') or die('can\'t open file_close');
        fwrite($rss, "</channel></rss>");
        fclose($rss);
}

function remove_tags($name) {
        $lines = file_get_contents('$name');
        str_replace("</channel></rss>", " ", $lines);
        $rss = fopen($name, 'w') or die('can\'t open file_remove');
        fwrite($rss, $lines);
}

function finish() {
        echo "The article <i> ";
        echo $_POST['title'];
        echo "</i>  has been added to the feed.<br>";
        echo "<a href=\"index.html\">Go Back</a> or <a href=\"rss.xml\">View the Feed</a>";
}
?>
</body></html>

根據str_replace上的文檔 ,您的str_replace行應該是:

$lines = str_replace("</channel></rss>", " ", $lines);

另外,你的remove_tags中的file_get_contents調用是因為引號而讀取一個不存在的文件(這就是當你把它寫回文件時$ lines為空的原因)。 那條線應該是這樣的:

$lines = file_get_contents($name);

你需要更換

str_replace("</channel></rss>", " ", $lines);

$lines = str_replace("</channel></rss>", " ", $lines);

在remove_tags函數中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM