2013-05-08 113 views
0

我想檢查一個文本文件的內容是否與另一個文本文件相同,如果不是,請將其中一個寫入另一個。我的代碼如下:被打印出來PHP - 在另一個文本文件中寫入文本文件內容

<?php $file = "http://example.com/Song.txt"; 
$f = fopen($file, "r+"); 
$line = fgets($f, 1000); 
$file1 = "http://example.com/Song1.txt"; 
$f1 = fopen($file1, "r+"); 
$line1 = fgets($f1, 1000); 
if (!($line == $line1)) { 
    fwrite($f1,$line); 
    $line1 = $line; 
    }; 
print htmlentities($line1); 
?> 

行,但內容沒有被寫在文件中。

有關可能是什麼問題的任何建議?

順便說一句:我使用000webhost。我認爲這是虛擬主機服務,但我已經檢查,應該沒有問題。我也在這裏檢查了fwrite函數:http://php.net/manual/es/function.fwrite.php。 請,任何幫助將非常aprecciated。

回答

1

你正在做什麼只適用於最多1000字節的文件。另外 - 使用「http://」打開第二個要寫入的文件,這意味着fopen內部將使用HTTP URL封裝器。這些是默認只讀的。你應該使用本地路徑打開第二個文件。或者,爲了使這更簡單,你可以這樣做:

$file1 = file_get_contents("/path/to/file1"); 
$path2 = "/path/to/file2"; 
$file2 = file_get_contents($path2); 
if ($file1 !== $file2) 
    file_put_contents($path2, $file1); 
+0

好的!我修好了路徑,它工作。沒有必要更改權限...無論如何都感謝! – fpolloa 2013-05-08 23:45:40

+0

很高興爲你工作,並且不用擔心。然而,習慣上接受幫助你的解決方案之一。謝謝! – 2013-05-08 23:53:20

+0

另外 - 如果你保留你的代碼,請注意1000字節的限制(來自fgets($ f,1000)) – 2013-05-08 23:53:59

1

在處理文件時,您會希望使用PATHS而不是URLS。
所以
$file = "http://example.com/Song.txt";成爲
$file = "/the/path/to/Song.txt";

下一頁:

$file1 = '/absolute/path/to/my/first/file.txt'; 
$file2 = '/absolute/path/to/my/second/file.txt'; 
$fileContents1 = file_get_contents($file1); 
$fileContents2 = file_get_contents($file2); 
if (md5($fileContents1) != md5($fileContents2)) { 
    // put the contents of file1 in the file2 
    file_put_contents($file2, $fileContents1); 
} 

此外,你應該檢查你的文件寫權限,那就是0666許可。

+0

謝謝!我將檢查'0666'權限。 – fpolloa 2013-05-08 23:39:19

+1

詳細信息:如果php進程擁有者擁有(或組擁有)該文件幷包含目錄,則不需要'0666'權限。 – 2013-05-08 23:40:00

+0

@TasosBitsios - 爲什麼他的事情變得複雜?讓這個人設置這個權限,我們不知道他在使用什麼樣的環境:) – Twisted1919 2013-05-08 23:40:57

相關問題