Hi guys,

I'm trying to change only one certain line in a file without changing anything else, but so far, I'm wiping out the entire file.

Here's how I've been trying to do it:

while(!feof($file)){
    $line = fgets($file);
    if($line == "Old Line 3"){
        $string = "New Line 3";
        fwrite($file, $string);
    }
}
fclose($file);

Any suggestions?

    You'll have to read the whole file into a string or array, make the change there, then write it back over the file. One way:

    $text = file($file, FILE_IGNORE_NEW_LINES)
    {
       foreach($text as $key => $line)
       {
          if($line == "Old Line 3")
          {
             $text[$key] = "New Line 3";
             // if you only expect one instace, do a break here:
             // break;
          }
       }
    }
    file_put_contents($file, implode("\n", $text));
    

      Hey NogDog,

      When I run that code, I get an "unexpected {" error.

      Though I'm not really familiar with some of the functions used here, it seems to me that there's no need for { starting after the first line of code.

      But when I try removing those {} I get other errors.

      Any ideas?

        Everyone's a critic. :p

        <?php
        $text = file($file, FILE_IGNORE_NEW_LINES);
        foreach ($text as $key => $line)
        {
           if ($line == "Old Line 3")
           {
              $text[$key] = "New Line 3";
              // if you only expect one instace, do a break here:
              // break;
           }
        }
        file_put_contents($file, implode("\n", $text));
        

          Yes, but what I'm saying is that even when I use this code, I get errors:

          Warning: file() expects parameter 1 to be string, resource given in /home/content/j/a/y/jay/html/1/chset.php on line 3
          
          Warning: Invalid argument supplied for foreach() in /home/content/j/a/y/jay/html/1/chset.php on line 5
          
          Warning: implode() [function.implode]: Invalid arguments passed in /home/content/j/a/y/jay/html/1/chset.php on line 12
          
          Warning: file_put_contents() expects parameter 1 to be string, resource given in /home/content/j/a/y/jay/html/1/chset.php on line 12

          The only thing I could think of was my $file, which is:

          $file = fopen("num.txt", "w");

          Ideas?

            The first parameter to file() is the path/name of the file. Change it to whatever you want it to be, or assign the string to $file. (There is no need for fopen() when using file() or file_put_contents().)

              Write a Reply...