Auto remove text from text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Auto remove text from text file

Post by SMR »

Im trying to figure out a way that I can get a text file to empty itself after so much text.
I have found some code that may have the same properties,but having a hard time figuring out how to substitute.
This code here removes images after however many you input.As one image gets added,the first created gets removed,and so on,moves up the line.
In this example here,5 images are made,
1.png - 2.png - 3.png - 4.png - 5.png
If 6.png is then made,this code removes 1.png,and so on,moves up the line as new images are created.I would like to do the same with text (lines) if possible.

Code: Select all

} 
if ($counterval > 5) {
	$deletebanner = (integer)$counterval - 5;
	$delete = 'banners/' . $deletebanner . '.png';
	unlink("$delete");
} 

?>
How can I use this to either clear a text file completely or move up the line.
I have a playlist.txt file that will get large and need to be cleared after awhile and rather than do it manually,would like code to do it for me.
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

D'ya want that file, playlist.txt have its oldest line removed or d'ya want the oldest playlist.txt to be deleted.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

creating a fifo structure to a text flatfile is quite simple.

Code: Select all

# assume $newtext is the new line to add.
$lines = file('filename.txt');
$fp = fopen('filename.txt', 'w');
if(count($lines) > 200)  // # of lines you want to keep in the file...
  unset($linesї0]);
$linesї] = trim($newtext, "\\0\\r\\n") . "\n";

$lines = implode('', $lines);

fwrite($fp, $lines);
fclose($fp);
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

n00b Saibot wrote:D'ya want that file, playlist.txt have its oldest line removed or d'ya want the oldest playlist.txt to be deleted.
I want the file playlist.txt to have its oldest line removed.
Example playlist.txt would look like this.

Code: Select all

Lacuna Coil||Comalies||Comalies
Lacuna Coil||Angel's Punishment||Comalies
Lacuna Coil||The Prophet Said||Comalies
Lacuna Coil||Entwined||Comalies
Lacuna Coil||Unspoken||Comalies
Lacuna Coil||The Ghost Woman And The Hunter||Comalies
Lacuna Coil||Tight Rope||Comalies
Lacuna Coil||Aeon||Comalies
Lacuna Coil||Self Deception||Comalies
Lacuna Coil||Humane||Comalies
Lacuna Coil||Daylight Dancer||Comalies
Lacuna Coil||Heaven's a Lie||Comalies
Lacuna Coil||Comalies||Comalies is the newest line of text,while Lacuna Coil||Heaven's a Lie||Comalies is the oldest line of text.
Would like it to remove lines of text as new entries are made.Im thinking the text file could save any amount of lines,but 30 would be good and then start removing lines.

Im not to good at php,is the code above what I want?The code posted by feyd ?
User avatar
carlmcdade
Forum Newbie
Posts: 24
Joined: Thu Dec 02, 2004 2:19 am
Location: sweden

Post by carlmcdade »

Off the top of my head so no checks done.

Code: Select all

<?php

$newLine = 'some new item here';

$arrList = file('playlist.txt');

$arrList = array_pop($arrList);

$handle = fopen('playlist.txt','w+');

fwrite($handle,$newLine);

foreach($arrList as $ v){

    $v = trim($v); //nasty whitespace and carriage return bug in file()
    fwrite($handle,$v);

}
fclose($handle);
?>
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

For some reason that doesnt look right.That looks to write to the file and I already have that.Im wanting to removes lines so the list doesnt grow too large.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

carlmcdade's doesn't take into account preserving x number of lines in the file. (his will also make the file all one line.. ;)) Try mine.
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

I am going to try yours,just have to figure out where ( what file ) to put it in lol
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

I think I may know.I have a config.php file that I think it might go into.WHere do you think the best place is?
Im thinking right after $PlayList = 'playlist_songs.txt';

Code: Select all

<?php
/*	Configuration File 
	This is the one stop spot to make changes to the Play List Script
*/
// Path to the play list source file
$PlayList = 'playlist_songs.txt';

/*	********** Static File Creation **********
	Should the output be stored in a static file (0), or dynamic (1)?
	Rendering the output to a static file, and using that file for
	display will speed up the rendering time of your page considerably
	as the user doesn't have to wait for the image size checks. Set
	this to 1 if you want a static copy of the playlist to be built
	everytime a new song is added to your playlist
*/
$BuildPlayListInclude = 1;
// Path to the output file for static pages
$PlayListInclude = 'playlist.html';
// The amount of songs to show on the static page
$StaticDisplayCount = 1;
// The format on the static page
$StaticIncludeFormat = 7;
// Path to an image to display when a cover image isn't provided by
// Amazon
$MissingAlbumImage = 'http://www.yourhost.com/play_list/missing_album_cover.jpg';

/*	********** Amazon IDs **********
	Replace 'silverspider-20' with your Amazon associated ID if you
	have one. You shouldn't need to change the Developer ID.
*/
$AssociateID	= 'silverspider2-20'; 
$DeveloperID 	= 'D1C7JYN1MZ5XTN';

/*	********** Various Artists **********
	The program will use 'Various Artists' when searching Amazon for
	any album listed below, this ensures the right album covers are
	shown, reducing	missing album images and bad searches.
	
	AJ Note: I may want to make this an array of arrays to account for
	albums that have various artists, but are stored within Amazon
	with a different artist name
	
	Important Notes
	- I used singles quotes around album names to cut down on the
	processing time but, that requires that single quotes within album
	names are properly escaped by using a backslash in front of each
	one. For example the album "Give 'Em the Boot" would be entered as
	'Give ''em the Boot'.
	
	- Album names are not case sensitive, so you can add them all as
	lower case, or upper case or mixed case if you want.
*/

$VariousArtists = 	array(
							'An Anthology of Big Band Swing',
							'Batman Forever',
							'Beneath the Icy Floe v5',
							'Beneath the Icy Floe V6',
							'Big Hits of the 80''s',
							'Billie, Ella, Lena, Sarah!',
							'Chef Aid: The South Park Album',
							'Dead Man Walking',
							'End of Days Soundtrack',
							'Excelsis: A Dark Noel',
							'Give ''em the Boot',
							'Godzilla Soundtrack',
							'Goth''s Undead',
							'Grosse Pointe Blank',
							'Headliners',
							'Headliners II',
							'In Their Own Words, Volume 1',
							'Joyride',
							'Less Than Zero (1987 Film) [SOUNDTRACK]',
							'Live After Death [Limited Edition]',
							'Living In Oblivion: The 80''s Greatest Hits - Volume 1',
							'Living In Oblivion: The 80''s Greatest Hits - Volume 2',
							'Lost Highway',
							'Memphis Belle',
							'Ministry Of Sound: The Annual Millennium Edition',
							'Monsters Of Goth',
							'O Brother, Where Art Thou?',
							'Priceless Jazz Sampler',
							'Projekt March & April 2000',
							'Pulp Fiction',
							'Pump Up the Volume',
							'Punk You - Vol. 1',
							'Queen Of The Damned [Soundtrack]',
							'Rise Above',
							'Romeo + Juliet: Music from the Motion Picture',
							'Rock: the Train Kept a Rollin''',
							'Stairway To Heaven, Highway To Hell',
							'Stone Free: A Tribute To Jimi Hendrix',
							'Stoned Immaculate',
							'The Newton Boys',
							'The Original Jazz Masters Series: Volume 1',
							'The Original Jazz Masters Series: Volume 2',
							'The Original Jazz Masters Series: Volume 3',
							);
		
/*	********** Character Translation **********
	Some non-english characters can cause problems when searching for
	an album on Amazon, so here is a list of these characters, and 
	the English equivalents. You can comment out those lines that you
	don't think you will need.
*/
$Translate = array(
					'À' => 'A',
					'à' => 'a',
					'Á' => 'A',
					'á' => 'a',
					'Â' => 'A',
					'â' => 'a',
					'Ã' => 'A',
					'ã' => 'a',
					'Å' => 'A',
					'å' => 'a',
					'Æ' => 'Ae',
					'æ' => 'ae',
					'Ç' => 'C',
					'ç' => 'c',
					'Ð' => 'D',
					'ð' => 'd',
					'È' => 'E',
					'è' => 'e',
					'É' => 'E',
					'é' => 'e',
					'Ê' => 'E',
					'ê' => 'e',
					'Ë' => 'E',
					'ë' => 'e',
					'Ì' => 'I',
					'ì' => 'i',
					'Í' => 'I',
					'í' => 'i',
					'Î' => 'I',
					'î' => 'i',
					'Ï' => 'I',
					'ï' => 'i',
					'Ñ' => 'N',
					'ñ' => 'n',
					'Ò' => 'O',
					'ò' => 'o',
					'Ó' => 'O',
					'ó' => 'o',
					'Ô' => 'O',
					'ô' => 'o',
					'ö' => "o",
					'Õ' => 'O',
					'õ' => 'o',
					'Ù' => 'U',
					'ù' => 'u',
					'Ú' => 'U',
					'ú' => 'u',
					'Ü' => 'U',
					'ü' => 'u',
					'Û' => 'U',
					'û' => 'u',
					'Ý' => 'Y',
					'ý' => 'y',
					);

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'm not sure, as I don't know where and when you get the "new" line in so the stack can be popped..
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

Yeah,just found another file that it may go into :?
These are the files I have......
CONFIG.PHP

Code: Select all

<?php
/*	Configuration File 
	This is the one stop spot to make changes to the Play List Script
*/
// Path to the play list source file
$PlayList = 'playlist_songs.txt';

/*	********** Static File Creation **********
	Should the output be stored in a static file (0), or dynamic (1)?
	Rendering the output to a static file, and using that file for
	display will speed up the rendering time of your page considerably
	as the user doesn't have to wait for the image size checks. Set
	this to 1 if you want a static copy of the playlist to be built
	everytime a new song is added to your playlist
*/
$BuildPlayListInclude = 1;
// Path to the output file for static pages
$PlayListInclude = 'playlist.html';
// The amount of songs to show on the static page
$StaticDisplayCount = 1;
// The format on the static page
$StaticIncludeFormat = 7;
// Path to an image to display when a cover image isn't provided by
// Amazon
$MissingAlbumImage = 'http://yourhost.com/play_list/missing_album_cover.jpg';

/*	********** Amazon IDs **********
	Replace 'silverspider-20' with your Amazon associated ID if you
	have one. You shouldn't need to change the Developer ID.
*/
$AssociateID	= 'silverspider2-20'; 
$DeveloperID 	= 'D1C7JYN1MZ5XTN';

/*	********** Various Artists **********
	The program will use 'Various Artists' when searching Amazon for
	any album listed below, this ensures the right album covers are
	shown, reducing	missing album images and bad searches.
	
	AJ Note: I may want to make this an array of arrays to account for
	albums that have various artists, but are stored within Amazon
	with a different artist name
	
	Important Notes
	- I used singles quotes around album names to cut down on the
	processing time but, that requires that single quotes within album
	names are properly escaped by using a backslash in front of each
	one. For example the album "Give 'Em the Boot" would be entered as
	'Give ''em the Boot'.
	
	- Album names are not case sensitive, so you can add them all as
	lower case, or upper case or mixed case if you want.
*/

$VariousArtists = 	array(
							'An Anthology of Big Band Swing',
							'Batman Forever',
							'Beneath the Icy Floe v5',
							'Beneath the Icy Floe V6',
							'Big Hits of the 80''s',
							'Billie, Ella, Lena, Sarah!',
							'Chef Aid: The South Park Album',
							'Dead Man Walking',
							'End of Days Soundtrack',
							'Excelsis: A Dark Noel',
							'Give ''em the Boot',
							'Godzilla Soundtrack',
							'Goth''s Undead',
							'Grosse Pointe Blank',
							'Headliners',
							'Headliners II',
							'In Their Own Words, Volume 1',
							'Joyride',
							'Less Than Zero (1987 Film) [SOUNDTRACK]',
							'Live After Death [Limited Edition]',
							'Living In Oblivion: The 80''s Greatest Hits - Volume 1',
							'Living In Oblivion: The 80''s Greatest Hits - Volume 2',
							'Lost Highway',
							'Memphis Belle',
							'Ministry Of Sound: The Annual Millennium Edition',
							'Monsters Of Goth',
							'O Brother, Where Art Thou?',
							'Priceless Jazz Sampler',
							'Projekt March & April 2000',
							'Pulp Fiction',
							'Pump Up the Volume',
							'Punk You - Vol. 1',
							'Queen Of The Damned [Soundtrack]',
							'Rise Above',
							'Romeo + Juliet: Music from the Motion Picture',
							'Rock: the Train Kept a Rollin''',
							'Stairway To Heaven, Highway To Hell',
							'Stone Free: A Tribute To Jimi Hendrix',
							'Stoned Immaculate',
							'The Newton Boys',
							'The Original Jazz Masters Series: Volume 1',
							'The Original Jazz Masters Series: Volume 2',
							'The Original Jazz Masters Series: Volume 3',
							);
		
/*	********** Character Translation **********
	Some non-english characters can cause problems when searching for
	an album on Amazon, so here is a list of these characters, and 
	the English equivalents. You can comment out those lines that you
	don't think you will need.
*/
$Translate = array(
					'À' => 'A',
					'à' => 'a',
					'Á' => 'A',
					'á' => 'a',
					'Â' => 'A',
					'â' => 'a',
					'Ã' => 'A',
					'ã' => 'a',
					'Å' => 'A',
					'å' => 'a',
					'Æ' => 'Ae',
					'æ' => 'ae',
					'Ç' => 'C',
					'ç' => 'c',
					'Ð' => 'D',
					'ð' => 'd',
					'È' => 'E',
					'è' => 'e',
					'É' => 'E',
					'é' => 'e',
					'Ê' => 'E',
					'ê' => 'e',
					'Ë' => 'E',
					'ë' => 'e',
					'Ì' => 'I',
					'ì' => 'i',
					'Í' => 'I',
					'í' => 'i',
					'Î' => 'I',
					'î' => 'i',
					'Ï' => 'I',
					'ï' => 'i',
					'Ñ' => 'N',
					'ñ' => 'n',
					'Ò' => 'O',
					'ò' => 'o',
					'Ó' => 'O',
					'ó' => 'o',
					'Ô' => 'O',
					'ô' => 'o',
					'ö' => "o",
					'Õ' => 'O',
					'õ' => 'o',
					'Ù' => 'U',
					'ù' => 'u',
					'Ú' => 'U',
					'ú' => 'u',
					'Ü' => 'U',
					'ü' => 'u',
					'Û' => 'U',
					'û' => 'u',
					'Ý' => 'Y',
					'ý' => 'y',
					);

?>
PLAYLIST_BUILDER.PHP

Code: Select all

<?
require_once("config.php");
include("playlist_display.php");

/*	Build list of recently heard songs from the information sent via
	GET by a media player plugin.
	Now Playing Plugin:
	  URL in Plugin:
	  http://dev.silverspider.com/amazon/list ... uilder.php
	Do Something Plugin: 
	  URL in plugin:
	  http://www.silverspider.com/includes/li ... hp?Title1=%%CURRENTSONGTITLE%%&Album1=%%CURRENTALBUM%%&Artist1=%%CURRENTARTIST%%
*/


/*	********** Check Playing Status **********
	Set the playing variable to the value set by Now Playing and 
	check to see if the Playing attribute is set to 0 (not 
	playing) or 1 (playing). If set to 1, proceed, otherwise stop.
*/
	
if(array_key_exists('Playing', $_GET)) {
	$Playing = $_GET["Playing"]; 
}

if ($Playing == 1) {
	/*	********** Grab New Song Info **********
		Take song information from the ping sent by the media player,
		replace the escaped single quotes with their un-escaped
		equivalent, then set the results of each in a new variable
	*/
	if(array_key_exists('Title1', $_GET)) {
		$Song = str_replace("''", "'", $_GET["Title1"]); 
	} else {
		$Song = str_replace("''", "'", $Title1); 
	}
	if(array_key_exists('Album1', $_GET)) {
		$Song = str_replace("''", "'", $_GET["Album1"]); 
	} else {
		$Album = str_replace("''", "'", $Album1); 
	}
	if(array_key_exists('Artist1', $_GET)) {
		$Song = str_replace("''", "'", $_GET["Artist1"]); 
	} else {
		$Artist = str_replace("''", "'", $Artist1); 
	}
	
	/*	********** Store New Song Info **********
		Store the song in the playlist format, using two pipes to
		separate the artist, song and album information, and a new line
		to denote separate records. Example:
		Artist Name||Song Name||Album Name
	 */
	$PlaylistEntry = $Artist . "||" . $Song . "||" . $Album . "\n"; 
	
	/*	********** Add Song Info to Play List **********
		Open the current playlist file, store its contents in a
		variable, then clear the play list file, write the current song to
		the file, finally append the previous entries to the end of the
		list
	*/
	$OpenPlayList = fopen( $PlayList, "r" );
	$Contents = fread( $OpenPlayList, filesize($PlayList) );
	fclose($OpenPlayList);
	
	$OpenPlayList = fopen ($PlayList, "r+");
	fwrite($OpenPlayList, $PlaylistEntry . $Contents);
	fclose($OpenPlayList);
	
	/*	********** Build Static Version ********** 
		Create the static version of the list according to the settings in
		the config file.
	*/
	if ($BuildPlayListInclude == 1) {
		show_playlist($StaticDisplayCount, $StaticIncludeFormat, 1);
	}
}
?>
PLAYLIST_DISPLAY.PHP

Code: Select all

<?
require_once("AmazonSearch.php");
require_once("config.php");

function show_PlayList($DisplayCount, $DisplayFormat, $BuildStatic) {
	global $PlayList, $AssociateID, $DeveloperID, $MissingAlbumImage, $OutputFormat, $PlayListInclude, $Translate, $VariousArtists;
	
	// Create an Amazon Search object
	$AS = new AmazonSearch($DeveloperID);
	
	// Function to check if an item is an array, getting around the
	// case-sensitive nature of in_array
	function in_array_anycase($Item, $Array) {
	   $Item = &strtoupper($Item);
	   foreach($Array as $Element) {
		   if ($Item == strtoupper($Element)) {
			   return true;
		   }
	   }
	   return false;
	}

	$Line = file($PlayList);
	if (!$Line) die( '<strong>Error: Cannot access play list.</strong>' );
	$TotalLength = count($Line);
	$i=0;

	while (($i+1) <= $DisplayCount) {
		if (($i+1) > $TotalLength) break;

		$CurrentSong = explode( '||', $Line[$i] );

		// Check to make sure we don't display an empty entry
		if ( ($CurrentSong == '||||') or (!$CurrentSong) ) continue;

		// Set album, artist and song variables, and replace
		// non-english characters for display and search results
		$Artist = strtr($CurrentSong[0], $Translate);
		$Title = strtr($CurrentSong[1], $Translate);
		$Album = strtr(trim($CurrentSong[2]), $Translate);		

		// Escape single quotes for JavaScript
		$ArtistJavaScript = str_replace("'", "''", $Artist);
		$AlbumJavaScript = str_replace("'", "''", $Album);

		/* clean up for allmusic.com - Not currently used
		$Artist_allmusic = str_replace(" ", "|", $Artist);
		$Artist_allmusic = str_replace(",", "", $Artist_allmusic); 
		*/
		
		// Clean up for Amazon query
		$ArtistAmazon = str_replace(" ", "%20", $Artist);
		$TitleAmazon = str_replace(" ", "%20", $Title);
		
		// Remove (Disc *) from the album name as it can mess up the
		// Amazon search, then trim the whitespace from the name
		$AlbumAmazon = trim(preg_replace("(\(Disc\s[0-9]\))", '', $Album));
		
		// For albums listed in $VariousArtists, set the Artist name
		// to 'Various Artists' when searching Amazon - this check is
		// case in-sensitive
		if (in_array_anycase($AlbumAmazon, $VariousArtists)) {
		   $ArtistAmazon = 'Various Artists';
		}		
		
		// Encode spaces for transmission to Amazon
		$AlbumAmazon = str_replace(" ", "%20", $AlbumAmazon);

	/* ---------------------------------------------------------------------- */
	
	/* Perform Keyword Search */
	$Result = $AS->DoKeywordSearch($ArtistAmazon . "+" . $AlbumAmazon, lite, music);
	
	if ($Result !== null)
	  {
		/* for ($increment = 0; $increment < count($Result); $increment++) {
		  $ResultRow = $Result[$increment];
	
		  $ASIN        = $ResultRow['Asin'];
		  $URL         = $ResultRow['Url'];
		  $UPC         = $ResultRow['Upc'];
		  $Price       = $ResultRow['OurPrice'];
		  $ProductName = $ResultRow['ProductName'];	
		} */
		
		// Grab the first album cover returned by Amazon
		$ProductImage = $Result[0]['ImageUrlMedium'];
		
		/*	********** Check Album Cover Image **********
			NOTE: Checking image size adds time/overhead to the script
		
			Check the width of the image provided by Amazon Sometimes,
			Amazon provides a single pixel image if it doesn't have
			an album cover
		
			If an album cover isn't returned, or the image is too
			small use the missing album cover image
		 */
		if (strlen(file_get_contents($ProductImage)) < 808 ) {
		  $ProductImage =  $MissingAlbumImage;		
		}
		/* Alternate (unused) methods */
		// Open the product image and read the first three bytes to 
		// determine if the file is a GIF - Amazon uses a single pixel
		// GIF for items that do not have an image
		/*
		$handle = fopen($ProductImage, "r");
		$contents = fread($handle, 3);
		fclose($handle);
		if ($contents == 'GIF' ){
		  $ProductImage =  $MissingAlbumImage;
		}
		*/
		/*
		// PHP's GetImageSize
		$ProductImageSize = getimagesize($ProductImage);
		$ProductImageWidth = $ProductImageSize[0];
		if ($ProductImage == '' || $ProductImageWidth < 45){
			$ProductImage =  $MissingAlbumImage;
		}
		 */
	  }
	
		// Create the link to Amazon
		$AmazonURL = 'http://www.amazon.com/exec/obidos/external-search?tag=' . $AssociateID . '&keyword=' . $ArtistAmazon . '+' . $AlbumAmazon . '&mode=music&ref=nosim';

		/*	********** Build Output ********** */
			switch ($DisplayFormat) {
				case 1: 	
					$SongOutput = '<a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /><span>' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</span></a>' . "\n";
				break;
				case 2: 	
					$SongOutput = '<a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /></a>' .  "\n" . '<a href="' . $AmazonURL .'" class="SSPLInfo">' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</a>' . "\n\n";
				break;
				case 3: 	
					$SongOutput = '<li><a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /><span>' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</span></a></li>' . "\n";
				break;
				case 4: 	
					$SongOutput = '<li><a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /></a>' .  "\n" . '<a href="' . $AmazonURL .'" class="SSPLInfo">' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</a></li>' . "\n\n";
				break;
				case 5: 	
					$SongOutput = '<div><a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /></a>' .  "\n" . '<a href="' . $AmazonURL .'" class="SSPLInfo">' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</a></div>' . "\n\n";
				break;
				case 6: 	
					$SongOutput = '<div class="SSPLImage"><a href="' . $AmazonURL .'"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /></a></div>' .  "\n" . '<div class="SSPLInfo"><a href="' . $AmazonURL .'">' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</a></div>' . "\n\n";
				break;
				case 7:    
                    $SongOutput = '<div class="SSPLImage"><a href="' . $AmazonURL .'"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /></a></div>' .  "\n" . '<div class="SSPLInfo"><a href="' . $AmazonURL .'">' . $Artist. '<br /></a> ' .  $Title . '<br />' . $Album  . '</div>' . "\n\n";
                break;
				default:
					$SongOutput = '<a href="' . $AmazonURL .'" class="SSPLImage"><img src="' . $ProductImage .'" alt="' . $AlbumJavaScript .'" /><span>' . $Title . ' by ' .  $Artist . ' from the album ' . $Album  . '</span></a>' . "\n";			
			}
		if ($BuildStatic == 1) {
			/*	********** Write Play List to Static File ********** */
			$SongOutputWrite .= $SongOutput;		
			$fp = fopen ($PlayListInclude, "w+") or die( '<strong>Error: Cannot open ' . $PlayListInclude . '</strong>' );
			fwrite($fp, $SongOutputWrite) or die( '<strong>Error: Cannot write to ' . $PlayListInclude . '</strong>' );
			fclose($fp) or die( '<strong>Error: Cannot close ' . $PlayListInclude . '</strong>' );
		} else {
			/*	********** Write Play List to Browser ********** */
			echo $SongOutput;
		}
	$i++;
	}
}
?>
Sorry for the big post.Im just now learning php and this is the project that is helping me learn.Iv made a few changes myself and it has been good so far.Im just trying to find a way for the playlist_songs.txt to keep itself small.Even though it is just text,after a while it will get pretty big,especially if listening to music all day :oops:
I do thank you for the help though :wink:
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

playlist_builder looks like the one to use... as it's writing the file to begin with.
User avatar
carlmcdade
Forum Newbie
Posts: 24
Joined: Thu Dec 02, 2004 2:19 am
Location: sweden

Post by carlmcdade »

feyd wrote:carlmcdade's doesn't take into account preserving x number of lines in the file. (his will also make the file all one line.. ;)) Try mine.
Well, I did say that it was off the top of my head. Here's a working snippet tested. Works and preserves the lines without counting them and without knowing how many there are.

I trim and replace the trailing ends of the lines to satisfy both Linux and Windows. There is some weird bug that not only hangs on to the new line character but also some other scrap in certain systems.

Code: Select all

<?php



$newLine = 'some new item here'."\n";

$arrList = file('playlist.txt');

$oldLine = array_pop($arrList);

$handle = fopen('playlist.txt','w+');

fwrite($handle,$newLine);

foreach($arrList as $v){

    $v = trim($v)."\n"; //nasty whitespace and carriage return bug in file()
    fwrite($handle,$v);

}
fclose($handle);


?>
SMR
Forum Newbie
Posts: 19
Joined: Fri Dec 17, 2004 1:11 am

Post by SMR »

Thank you for your contribution.
But I still dont think this is what I need.
I already have the means of writing the text to the playlist_songs.txt
What I need to do is make it so it only writes so much and starts removing after so many lines.
Like I posted above,if I have it list 30 lines,when line 31 is made,line 1 is removed.When line 32 is made,line 2 removes,and so on.

I tried the code feyd posted.I put it in playlist_builder.php but then the script didnt work at all.I may have put it in the wrong place,or,,,,,,,, :?

Maybe I need to combine the code with another from the file.I dont know,still a noob to all this.
User avatar
carlmcdade
Forum Newbie
Posts: 24
Joined: Thu Dec 02, 2004 2:19 am
Location: sweden

Post by carlmcdade »

I guess if you like feyd code then you should go with it but I can't figure out how it fits in either. He will have to jump in. But in the mean time this definately works.

Code: Select all

<?php
$OpenPlayList = file($PlayList);
	$oldLine = array_pop($OpenPlayList);
	$handle = fopen($PlayList,'w+');
	foreach($OpenPlayList as $v){

	    $v = trim($v)."\n"; //nasty whitespace and carriage return bug in file()
	    fwrite($handle,$v);

	}
	fclose($handle);

	$OpenPlayList = fopen( $PlayList, "r" );
	$Contents = fread( $OpenPlayList, filesize($PlayList) );
	fclose($OpenPlayList);
    
    $OpenPlayList = fopen ($PlayList, "r+");
    fwrite($OpenPlayList, $PlaylistEntry . $Contents);
    fclose($OpenPlayList);


?>
Post Reply