I want PHP to loop, line by line, through a big 100MB text file, and append the phrase "Good Quality!" to any line with the word "car" in it. Here's an example (the first 4 lines of a 500,000-line text file):

Original file:

Brand new motor boat.
Used gold colored car.
Bag of sweet candy.
Shiny car with windows.

What I want:

Brand new motor boat.
Used gold colored car. Good Quality!
Bag of sweet candy.
Shiny car with windows. Good Quality!

I experimented with FOPEN and FWRITE, as well as using foreach(preg_split("/((\r?\n)|(\r\n?))/",$big_file) as $line with the "file_get_contents/file_put_contents" functions and no matter what I tried or did, I couldn't get anything to work. For some reason, I can't wrap my head around making PHP loop through a file line by line and making changes only to certain lines.

Thank you in advance!

    [man]fgets[/man] would be easier for reading line-by-line. I have no idea what you tried or did, but you'd need to create a new file and write all the lines (changed as needed) to that.

      Thank you, but how, though? Most of my day was spent on google, learning fopen, fwrite, and fgets examples... but none showed how to concurrently do php processing looping line by line, and then writing.

      I know you're the experts on this forum are not too 'big' on providing the code (i.e. "teaching a man to fish"), but in this one instance, would you mind showing me how to loop through.

      I can do this part:
      if(stristr($line,'car)) { $line = $line." Good Quality!"; }

      But, I'm thinking even that is wrong, because of the reading/appending.

      Anyway, I would greatly appreciate it if you would throw me a couple lines of code :-)

        An example of using a loop to read a file line by line is on the manual page for [man]fgets[/man]. The example justs outputs the line but you can do anything else in there instead (such as searching it, appending to it, or writing it to another file).

        Open a file for reading, open another for writing.

        Inside the loop,
        read a line from the first file,
        process it,
        and write it to the second file.

          Thanks TurdPacket.

          Just a side note to the folks viewing -- see? That's how ya' do it. Pretend to grovel (notice how I called him an "expert"), and then ya' lie and say how you have been trying all day on Google LOL -- I haven't even googled anything yet!

          The anal-diamond Packet answered my question, and I'm good to go.

          Yes, I'll be banned, that's why I picked the name "php_forever" because of the irony.

            Write a Reply...