Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBen Bastow
24,657 PointsAdding a string to each line but the first
Hi!
I am trying to add a string to the end of eachline. So far this works. However I dont want the string to be added to the end of the first line. How can I do this?
So far i have got:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
2 Answers
Codin - Codesmite
8,600 Points<?php
$fileName = "file.txt";
$EOLString="string \n";
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
$x = 0;
foreach($lines as $line){
if ($x > 0) {
$lines[$x] .= $EOLString;
file_put_contents("inputfile.txt", $lines[$x], FILE_APPEND);
}
$x++;
}
?>
*Edited as my last answer was flawed :)
This code will add the file to an array and then append each line of the array to a new file, using if statements to skip the first line.
Ben Bastow
24,657 PointsAshely! thank youu!! this works!! I also found another way to do this by setting the fgets to a variable in the whileloop before the counter as this then gets the line and goes to the second line :)!! thank you for helping me!!
Ben Bastow
24,657 PointsBen Bastow
24,657 PointsHi ashley Thanks for the reply!!
However, It didn't work and i have no clue why :(
Codin - Codesmite
8,600 PointsCodin - Codesmite
8,600 PointsI realised the mistake with my last answer, even when the if is true it will start on the first line of the file.
Try this instead: