How to create a basic news system



by Administrator author list

Now we are able to post news and store them in the filesystem. However it is important to display the posts as well. To do this we will create a new file, let's say index.php which is responsible for displaying posts on the screen.

This code needs to check the news directory, read all files in it and displays the content. First of all we need to create a function which collects all available files from the news directory and after the list should be sorted to display news in chronological order. To do this we use opendir and readdir functions and we put all names into an array which is not a directory. When all files were processed we sort the array. The function is quite simple:

 

function getNewsList(){

$fileList = array();

// Open the actual directory
if ($handle = opendir("news")) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!
is_dir($file)) {
$fileList[] = $file;
}
}
}

rsort($fileList);

return
$fileList;
}
?>

 

Now it's time to display the posts. Se we create a HTML page where we will put the messages in a table. In the first row we will display the post title and the time. Next we pot the post content in a new row. We repeat this steps for each file.

To read back posts we use the file function which reads the file content into an array. Each line will be a separate array element. As we put title in the first line and the time in the second line so we know that the first 2 lines contains important information. We will save it in an other variable and the remove the first 2 elements from the array. Next we will walk through the array and concatenate lines into a string. Now we have the 3 important variable and so we can display them and go back and take the next file.

The code which processes and displays the files looks like this:

 

$list = getNewsList();
foreach (
$list as $value) {
$newsData = file("news/".$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset (
$newsData['0']);
unset (
$newsData['1']);

$newsContent = "";
foreach (
$newsData as $value) {
$newsContent .= $value;
}

echo
"$newsTitle
$submitDate"
;
echo
"".$newsContent.
"


";
}
?>

 

That's all.

 

Download:

You can download a small news system from the download section.

 

Full code:

On the next page you can find the full source code of the admin.php and index.php



article index
page 1 : untitled page
page 2 - current : The news page
page 3 : Full source code


Tags: php news publishing, news script, news publishing, php news script

Php Toys - 2006 - Php resources, scripts and tutorials - Privacy Policy
Insurance Index - Tutorial collection - Forex trading, brokers, reviews - Mortgage payment calculator
{THEMEDISCLAIMER}
Render time: 0.1252 sec, 0.0154 of that for queries. DB queries: 25.