i want to delete first 5 lines in a 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

Post Reply
brae2009
Forum Newbie
Posts: 1
Joined: Sun May 13, 2012 11:16 am

i want to delete first 5 lines in a text file

Post by brae2009 »

hello
iam new in php

i want to reed first 5 lines in text file

then i want to delete first 5 lines in a text file "1.txt"

i tried multi codes before

i want to make a iframe from first 5 lines in the text then delete them and update the file


Code: Select all

<?php 
$myFile = "1.txt";
$lines = file($myFile);//file in to an array
 { 
print "<iframe width=300 height=260 src=" . $line[1] . "></iframe><br />\n"; 
print "<iframe width=300 height=260 src=" . $line[2] . "></iframe><br />\n"; 
print "<iframe width=300 height=260 src=" . $line[3] . "></iframe><br />\n"; 
 }

$File = "1.txt"; 
 $Handle = fopen($File, 'w');
delete($Handle, $lines[1]);
delete($Handle, $lines[2]);
delete($Handle, $lines[3]); 
 fclose($Handle); 

 ?>
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: i want to delete first 5 lines in a text file

Post by mecha_godzilla »

Hi,

You can count the number of values in an array like this:

Code: Select all

$number_of_lines = count($array);
so if you want to output the first five lines you just need to do this:

Code: Select all

if ($number_of_lines >= 1) {
    for ($i = 1; ($i <= $number_of_lines && $i <= 5); $i++) {
        echo $array[$i - 1]; // remember that first array value begins at [0] not [1]
    }
}
If you want to output a new file that doesn't contain the first five lines, you'll have to do something like this:

Code: Select all

$new_text = NULL;
if ($number_of_lines > 5) {
    for ($i = 6; $i <= $number_of_lines; $i++) {
        $new_text .= $array[$i - 1];
    }
}
echo $new_text;
The .= operator concatenates (appends) whatever was already in $new_text with the next value, so if you had

Line 1: Hello<lnbr>
Line 2: World!<lnbr>

then $new_text would look like

Hello<lnbr>World!<lnbr>

Note that when you use file() to read in the contents of a file, the new line/returns are kept so you don't have to add them back in afterwards. To complete this script you'll just need to use fwrite() - more details can be found here:

[url]http://uk.php.net/manual/en/[url]

HTH,

Mecha Godzilla
Post Reply