Home >Backend Development >PHP Tutorial >PHP code to automatically publish news_PHP tutorial
News files are stored in a fixed directory in text file .txt format, and news release can be completed automatically.
The process consists of two parts:
The first is the display of news, which is implemented by the shownews.php script. The code is as follows:
〈table border="0" width="90%"〉
〈?php
//Put the title of the news in the first line of the news file
//The news file must be a text file (.txt)
$newspath = "./news/"; // Modify the directory where news files are stored
$newsfile = array();
$hd = dir($newspath);
while( $filename = $hd-〉read() ) {
$s =strtolower($filename);
if (strstr($s,".txt")) {
$lastchanged=filemtime($newspath.$filename);
$newsfile[$filename] = $ lastchanged;
}
}
arsort($newsfile);
for(reset($newsfile); $key = key($newsfile); next($newsfile)) {
print "〈tr〉〈td〉n";
$fa = file($newspath.$key);
$s=trim($fa[0]);
$s=htmlspecialchars($s );
$lk=strlen($key);
$a=substr($key,0,$lk-4);
$s="〈a href="./pubnews.php ?id=".$a."" target=_blank〉".$s."〈/a〉";
print $s." n";
print "(".date("Y year m on d - H:i:s",$newsfile[$key]).")
n";
print "〈/td〉〈/tr〉";
}
$hd-〉close();
?〉
〈/table〉
Put the code where the news is displayed:
〈?php
require "./shownews.php";
?〉
The second part is the release of news, which is implemented by the puppetnews.php script. The code is as follows:
〈?php
if ($id=="")
{
Header("Location: ./shownews.php");
}
?〉
〈html〉
〈head〉
〈meta content="chenqiang" name=Author〉
〈?php
$filename="./news/".$id.".txt";
$fa=file($filename);
$n=count($fa);
$s=trim($fa[0]);
$s=htmlspecialchars($s);
$t=" - news by waterwall";
print "〈title〉". $s.$t."〈/title〉n";
?〉
〈/head〉
〈body〉
〈?php
//Output text title
print "〈blockquote〉n";
print "〈b〉〈center〉".$s."n";
print "〈/center〉〈/b〉
〈p〉n";
//Output text body
for ($i=1;$i〈$n;$i+=1)
{
$s=chop($fa[$i]);
$s=htmlspecialchars($s);
$s=trim($s);
print " ".$s."
n";
}
print "〈/ p〉〈/blockquote〉n";
?〉
〈/body〉
〈/html〉
It can also be implemented using a database, this is only in the form of a file.