mikey balls
mikey balls

Reputation: 115

How can I write to a file line by line or similar?

In the code below, I simply replace all single quotes with double quotes from the original file.

I got most of it done, I just need to write it to a file now.

Should I store all the lines in memory and then write.

Or write line by line?

Which way is best

<?php

    // http://stackoverflow.com/questions/5299471/php-parsing-a-txt-file
    // http://stackoverflow.com/questions/15131619/create-carriage-return-in-php-string
    // http://stackoverflow.com/questions/2424281/how-do-i-replace-double-quotes-with-single-quotes


    $txt_file    = file_get_contents('../js/a_file.js');
    $rows        = explode("\n", $txt_file);
    array_shift($rows);

    foreach($rows as $row => $data)
    {
        $data = str_replace("'", '"', $data);

        // echo "" . $row . " | "  . $data . "\r\n";

        // fwrite($myfile, $txt);

    }

Upvotes: 0

Views: 74

Answers (3)

Mario
Mario

Reputation: 420

You can use in your code:

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

For example:

$txt_file    = file_get_contents('../js/a_file.js');
$rows        = explode("\n", $txt_file);
array_shift($rows);

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

foreach($rows as $row => $data)
{
    $data = str_replace("'", '"', $data);

    fwrite($myfile, $data );

 }

 fclose($myfile);

Upvotes: 0

u_mulder
u_mulder

Reputation: 54796

All you operations are redundant:

$result = file_put_contents(
    '../js/a_file.js',
    str_replace("'", '"', file_get_contents('../js/a_file.js'))
);

Upvotes: 1

Tony Markov
Tony Markov

Reputation: 55

you can to write in file with

<?php 
$content = str_replace("'", '"', file_get_contents('../js/a_file.js'));
$myfile = "../js/a_file.js";
file_put_contents($myfile , $content);
?>

Upvotes: 0

Related Questions