Creating a News System with PHP - Part 1 - Displaying the News
(Page 4 of 4 )
So, we have a way to get the data from our browser into a text file. Now all we need to do is display the news. This is the simple part. Basically, all we are going to do is read the file into an array. Then, because the newest information is at the end of the array, we need to reverse the order of the data in the array. Then just separate our data into its different parts. Last, we display it. So, let's do it.
First step, let's get the data into an array. For that we will use the file function. This function reads a file into an array. Each line in the file becomes an element in the array. Exactly what we need.
<?php $data = file('news.txt'); ?> |
Next, we want to reverse the array so that we are reading the newest news first. For that we will use the array_reverse function. Simple eh?
<?php $data = file('news.txt'); $data = array_reverse($data); ?> |
Ok, so we have the data back out of the text file. What we need to do now is split each line back up into a date, a name and the news. The explode function will do exactly what we want. So, we will run a loop for as many elements as there are in our array and split each element with the explode function. While we are at it, we will echo out our results. I am also using the trim function on each element to remove the newline at the end.
<?php $data = file('news.txt'); $data = array_reverse($data); foreach($data as $element) { $element = trim($element); $pieces = explode("|", $element); echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b><BR><BR>"; } ?> |
Place that into your page wherever you want the news to display, and bam you've got news.
Thanks for tuning in for this first lesson on creating a news system in PHP. In the next lesson we will start saving all our data in a database. Till then, keep coding!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |