简体   繁体   中英

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);

    }

All you operations are redundant:

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

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);
?>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM