2012-02-26 33 views
0

下面的代码输出格式良好的文本文件。但是它也在文本文件的末尾添加了一个额外的字符 - 我假设一个\ r或\ n字符。我已经试过sed'$ d'但是这不起作用。当我在编辑器中打开输出文件(load_data_infile.txt)时,我将光标定位在文件的最后一行文本之后,它说我处于“奇怪的15”行。我怎样才能在14行文件中有15行?fgets增加了一个额外的行来输出文件?

我的问题是这些:1)什么是导致行“15的14”和2)我怎样才能防止它被写入或一旦它被删除?

谢谢!

<?php 

$file_write_output = fopen("load_data_infile.txt", "w") or die ("can't open load_data_infile.txt for writing"); 
$file_read_input = fopen("http://file.txt", "r") or die ("can't open file"); 

//perform the loop through the file - read the input file line by line with fgets function 

while (!feof($file_read_input)) { 

$input = fgets($file_read_input); 


echo "$input"; 

fwrite($file_write_output,$input); 

} 

fclose($file_write_output); 

fclose($file_read_input); 

?> 

<?php 

//strip out the header of load_data_infile.txt file 


exec("sed -i '1d' load_data_infile.txt"); 


?> 
+0

如果您正在使用UNIX,你可以用'LS -l'来检查lenghts是相同的,我不相信的fwrite()写任何东西比。 – SteAp 2012-02-26 22:30:49

+0

读取数据。 'od -c'会显示字符并将空格\不可打印的字符转换成您可以看到的东西。 – 2012-02-26 23:03:08

+0

嗨,谢谢 - od -c在命令行执行?我需要指定文件名吗? – tomish 2012-02-27 04:23:42

回答

0

试试这个:

$content = file_get_contents('http://file.txt'); 

if ($file !== false) { 
    return $file; 
} 

if (file_put_contents('load_data_infile.txt', $content, LOCK_EX)) { 
    // Success 
} 

PHP文件: PHP file_get_contentsPHP file_put_contents

+0

谢谢 - 这是否取代我的循环? – tomish 2012-02-27 04:24:04

0

下面的代码工作!

<?php 
    $raw_data = file_get_contents('http://file.txt'); 
    $trimmed_raw_data=trim($raw_data); 
    echo $trimmed_raw_data; 
    if (file_put_contents('load_data_infile.txt', $trimmed_raw_data, LOCK_EX)) 
?>