Jump to content

I need help on a news script.


cloevvold

Recommended Posts

I have this script:

 

<?php


// This function reads all available news
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;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
   <link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>

    
    <table width="100%">
    <?php
    
      $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 "<tr><th align='left'>$newsTitle</th><th align='right'>$submitDate</th></tr>";
      	echo "<tr><td colspan='2'><br>".$newsContent."<br/><br><hr size='1'/><br></td></tr>";
      }
    ?>

 

It reads news from flat (text files)

I need to have pagination on this script, so it only shows 5 news on each page.

And I would like to be able to show the last news, that only shows 1 news, "the latest one" on another page, with a link under "read more news".. that points to the page with all news.

 

I really hope someone can help me here... Im stuck.. and should have this out soon..

Link to comment
Share on other sites

How are news clippings posted? To a script, or just with Notepad?

 

If they're posted via a script, have an index file (like news_index.txt). This will be your mini-database.

You could save each entry as Title|date|Author...

Then the entries would all be listed chronologically.

 

Then just grab the index file with file(), and parse each line. It's much quicker than making so many filesystem calls.

 

If postings are just saved with Notepad, then this will be a little more complex.

Link to comment
Share on other sites

The only files in this script is index.php... the script I have posted.. and admin.php, to post news.

And all newsfile get saved in a own textfile (notepad), one notepad file per news.

 

Im sorry.. Im really new at this, so I didnt understand all that you wrote :(

 

Hope it is possible to make this work  :-\

Link to comment
Share on other sites

Then just grab the index file with file(), and parse each line. It's much quicker than making so many filesystem calls.

According to her posted code, this is already being done.

 

Since you have a submit date, if it's in a valid format, you could sort on that "column" of your data. Let's deal with the biggest issue first: pagination. See if this helps you some:

<?php
$list = getNewsList();

// Start pagination variables
$total = count($list);
$page = isset($_GET['p']) && ctype_digit($_GET['p']) ? $_GET['p'] : 1; // Default to page 1
$limit = 5; // Number per page
$page_count = ceil($total / $limit);
$start_key = ($page * $limit) - $limit;
$end_key = $start_key + $limit;

if ($page > $page_count) // Default to max page, or you'll have errors if they go over
{
  $page = $page_count;
}
elseif ($page < 1) // likewise for negative numbers
{
  $page = 1;
}
// End pagination variables

// Print pagination
echo "Pages: ";
$p_out = array();
for ($i = 1; $i <= $page_count; $i++)
{
  if ($i == $page) // current page, so don't link it
  {
    $p_out[] = "<span class=\"curr_page\">{$i}</span>";
  }
  else // create link to this page
  {
    $p_out[] = "<a href=\"?p={$i}\">{$i}</a>";
  }
}
echo implode(' | ', $p_out);

// Output your 5 records for this page
echo "<table>\n";
for ($s = $start_key; $s <= $end_key; $s++)
{
  // Do your output however you like
  $newsData = file("news/" . $list[$s]);
  $newsTitle  = $newsData[0];
  $submitDate = $newsData[1];	
  unset ($newsData['0']);
  unset ($newsData['1']);

  $newsContent = "";
  foreach ($newsData as $value) 
  {
    $newsContent .= $value;
  }
      	
  echo "<tr><th align='left'>$newsTitle</th><th align='right'>$submitDate</th></tr>";
  echo "<tr><td colspan='2'><br>".$newsContent."<br/><br><hr size='1'/><br></td></tr>";

}
echo "</table>\n";
?>

 

Hope this helps some.

Link to comment
Share on other sites

Looks like obsidian code works... :)

But there is some issues..

Now I have 7 news in my page.. and when I go to page 2 it shows the last 2 posted.. and after that it shows several lines (the lines that seperates the news)..

Looks like this:

 

news.JPG

 

And is it possible to make pagination appear on the bottom of the news.. in the center?

 

Thanks in advance :)

 

Link to comment
Share on other sites

Looks like obsidian code works... :)

But there is some issues..

Now I have 7 news in my page.. and when I go to page 2 it shows the last 2 posted.. and after that it shows several lines (the lines that seperates the news)..

 

And is it possible to make pagination appear on the bottom of the news.. in the center?

 

Thanks in advance :)

 

Just put the // Print Pagination section under the article display and put

echo "<center>";
// Print pagination section goes here
echo "</center>";

Link to comment
Share on other sites

OK, here's a couple tweaks that should help you out:

<?php
$list = getNewsList();

// Start pagination variables
$total = count($list);
$page = isset($_GET['p']) && ctype_digit($_GET['p']) ? $_GET['p'] : 1; // Default to page 1
$limit = 5; // Number per page
$page_count = ceil($total / $limit);
$start_key = ($page * $limit) - $limit;
$end_key = ($start_key + $limit) - 1;
$max_key = $total - 1;

if ($page > $page_count) // Default to max page, or you'll have errors if they go over
{
  $page = $page_count;
}
elseif ($page < 1) // likewise for negative numbers
{
  $page = 1;
}

if ($end_key > $max_key)
{
  $end_key = $max_key;
}
// End pagination variables

// Output your records for this page
echo "<table>\n";
for ($s = $start_key; $s <= $end_key; $s++)
{
  // Do your output however you like
  $newsData = file("news/" . $list[$s]);
  $newsTitle  = $newsData[0];
  $submitDate = $newsData[1];	
  unset ($newsData['0']);
  unset ($newsData['1']);

  $newsContent = "";
  foreach ($newsData as $value) 
  {
    $newsContent .= $value;
  }
      	
  echo "<tr><th align='left'>$newsTitle</th><th align='right'>$submitDate</th></tr>";
  echo "<tr><td colspan='2'><br>".$newsContent."<br/><br><hr size='1'/><br></td></tr>";

}
echo "</table>\n";

// Print pagination
echo "<div style=\"text-align: center;\">\n";
echo "Pages: ";
$p_out = array();
for ($i = 1; $i <= $page_count; $i++)
{
  if ($i == $page) // current page, so don't link it
  {
    $p_out[] = "<span class=\"curr_page\">{$i}</span>";
  }
  else // create link to this page
  {
    $p_out[] = "<a href=\"?p={$i}\">{$i}</a>";
  }
}
echo implode(' | ', $p_out);
echo "</div>\n";
?>

 

Let me know if that looks better. Also, if you want to change the number shown on the page, just change the LIMIT variable up top.

 

Good luck!

Link to comment
Share on other sites

Just put the // Print Pagination section under the article display and put

echo "<center>";
// Print pagination section goes here
echo "</center>";

 

Actually, you should stay away from <center> tags, as they are deprecated. Use a div with CSS centering for best results, as I showed in my previous post.

Link to comment
Share on other sites

As for the blank entries, replace the code below:

 

// Output your records for this page
echo "<table>\n";
for ($s = $start_key; $s <= $end_key; $s++)
{
if (file_exists("news/" . $list[$s])) {
  // Do your output however you like
  $newsData = file("news/" . $list[$s]);
  $newsTitle  = $newsData[0];
  $submitDate = $newsData[1];	
  unset ($newsData['0']);
  unset ($newsData['1']);

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

  echo "<tr><th align='left'>$newsTitle</th><th align='right'>$submitDate</th></tr>";
  echo "<tr><td colspan='2'><br>".$newsContent."<br/><br><hr size='1'/><br></td></tr>";
}
}
echo "</table>\n";

Link to comment
Share on other sites

Looks much better... Only 2 things I want to get sorted out.. Would like pagination to display at the bottom of the page... under the last news on the page.. not on the button... :)

 

And If you know about a way I can display the latest news (only one) on another page... with a link that says: "read more news" that goes to the main news page :)

Link to comment
Share on other sites

Put this on the new page.

 

<?php
$news_link = "http://yoursite.com/link_to_your_news.php";

// This function reads all available news
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;
}

?>

<?php
$list = getNewsList();

echo "<table>\n";
  // Do your output however you like
  $newsData = file("news/" . $list[0]);
  $newsTitle  = $newsData[0];
  $submitDate = $newsData[1];	
  unset ($newsData['0']);
  unset ($newsData['1']);

  $newsContent = "";
  foreach ($newsData as $value) 
  {
    $newsContent .= $value;
  }
      	
  echo "<tr><th align='left'>$newsTitle</th><th align='right'>$submitDate</th></tr>";
  echo "<tr><td colspan='2'><br>".$newsContent."<br/><br><hr size='1'/><br></td></tr>";
  echo "<tr><td colspan='2'>See more news at: {$news_link}</td></tr>";
echo "</table>\n";
?>

Link to comment
Share on other sites

As for the blank entries, replace the code below:

 

Not trying to nitpick here, but there's really no need for the file_exists() call. This opens up an additional apache subroutine on every call, which really isn't necessary since we already have gathered all the files into our array. If you'll replace my original code with my most recent one, the blanks should be gone, since I've created a $max_key variable that helps with that, and the pagination is also set to appear at the bottom of the page.

Link to comment
Share on other sites

And If you know about a way I can display the latest news (only one) on another page... with a link that says: "read more news" that goes to the main news page :)

 

The function filectime() will get you the create time of the file, so if you are looping through a directory, you can use this to easily gather the file that was last created (your most recent news):

<?php
$dir = 'news/';
if ($handle = opendir($dir) !== FALSE)
{
  $rec_file = '';
  $c_time = 0;
  while ($file = readdir($handle))
  {
    if ($file != '.' && $file != '..')
    {
      if (filectime($dir . $file) > $c_time)
      {
        $c_time = filectime($dir . $file);
        $rec_file = $file;
      }
    }
  }
}
?>

 

When that script ends, $c_time will hold the creation time of the most recent file, and the filename is in $rec_file.

Link to comment
Share on other sites

Im really sorry... I cant seems to get it in :( ... can u show me how?? ...

This is where I want my latest news want to be shown on the mainpage of the site:

 

<div class="box">
        <br /><br />
	<strong>Latest News:</strong><br />
	<br />latest news will be shown here.
	</div>

 

This is in the index.php in root of the site..

The news page is: nyheter/index.php

Link to comment
Share on other sites

My last post only shows how to pull the name of the most recently created article. You would still need to pull the information as you have with your others. So, plug that above code in where you want to show the article, and then follow it with your normal. Also, I would recommend writing a function that will parse out your news feed for you so you don't have to duplicate code all over the place:

<?php
function parseNews($file)
{
  $rows = file($file);

  $res = array();
  $res['title']  = $rows[0];
  $res['date'] = $rows[1];	
  unset ($rows['0']);
  unset ($rows['1']);

  $content = '';
  foreach ($rows as $row) 
  {
    $content .= $row;
  }

  $res['content'] = $content;
  return $res;
}

$art = parseNews('news/' . $rec_file);
$title = $art['title'];
$date = $art['date'];
$content = $art['content'];
?>

 

Then, you can output it however you like.

Link to comment
Share on other sites

No problem... I'm not trying to be a bear, but at the same time, I like to try to point people to a solution without writing every line when I can. Here is a possible solution that you can work with and modify to your needs. I'll put all the pieces together, and you can ask me if you have any specific questions:

<?php
function parseNews($file)
{
  $rows = file($file);

  $res = array();
  $res['title']  = $rows[0];
  $res['date'] = $rows[1];	
  unset ($rows['0']);
  unset ($rows['1']);

  $content = '';
  foreach ($rows as $row) 
  {
    $content .= $row;
  }

  $res['content'] = $content;
  return $res;
}

$dir = 'news/';
if ($handle = opendir($dir) !== FALSE)
{
  $rec_file = '';
  $c_time = 0;
  while ($file = readdir($handle))
  {
    if ($file != '.' && $file != '..')
    {
      if (filectime($dir . $file) > $c_time)
      {
        $c_time = filectime($dir . $file);
        $rec_file = $file;
      }
    }
  }
}

$art = parseNews($rec_file);

echo "<div class=\"box\">\n";
echo "<br /><br />\n";
echo "<strong>Latest News:</strong><br />\n";
echo "<br />\n";
echo "<table>\n";
echo "<tr><th align='left'>$art[title]</th><th align='right'>$art[date]</th></tr>";
echo "<tr><td colspan='2'><br>$art[content]<br/><br><hr size='1'/><br></td></tr>";
echo "</table>\n";
echo "</div>\n";
?>

 

This should at least give you the idea of where you can head. Like I said, let me know if you have questions.

Link to comment
Share on other sites

I have now puttet this code on my frontpage, but I cant get the last news to be shown there, and cant se any link to go to the main newspage to read the rest of the news.

It looks like this:

 

newserror.JPG

 

I understand that You dont want to write every single line that is nedded to get this to work, But I really think I need it ;)

 

 

 

 

 

Link to comment
Share on other sites

n~ link=topic=167971.msg741949#msg741949 date=1195467749]

I think there is some path error, not too sure though maybe in this line

$dir = 'news/';

 

The path to the folder that the news text files is: nyheter/news/

And I have changed the path to that.. But I still have this error.. And the last news are not shown?

Link to comment
Share on other sites

n~ link=topic=167971.msg741949#msg741949 date=1195467749]

I think there is some path error, not too sure though maybe in this line

$dir = 'news/';

 

The path to the folder that the news text files is: nyheter/news/

And I have changed the path to that.. But I still have this error.. And the last news are not shown?

 

So, when you post the code above and change the directory line to: [mono]$dir = 'nyheter/news/';[/mono], it still has the same error, or is it now a different error? The fact that you're running on a Windows box may make reading the directories slightly different, but since we got it to work on the other page, I think the methodology is sound.

 

It appears that your web root is set to C:\wamp\www\, correct? If so, what is the full path to the news feeds? If it is C:\wamp\www\nyheter\, then rather than simply referencing 'nyheter/news/', you may need to have '../nyheter/news/' since you are already within the "noram" directory.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.