2013-05-08 110 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

相关问题