在下面的代码中,我只是用原始文件中的双引号替换所有单引号。
我完成了大部分工作,我现在只需将其写入文件。
我应该将所有行存储在内存中然后写入。
还是逐行写?
哪种方式最好
<?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);
}
答案 0 :(得分:1)
所有操作都是多余的:
$result = file_put_contents(
'../js/a_file.js',
str_replace("'", '"', file_get_contents('../js/a_file.js'))
);
答案 1 :(得分:0)
你可以用
写入文件<?php
$content = str_replace("'", '"', file_get_contents('../js/a_file.js'));
$myfile = "../js/a_file.js";
file_put_contents($myfile , $content);
?>
答案 2 :(得分:0)
您可以在代码中使用:
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
例如:
$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);