2

我需要打开一个文件,替换一些内容(12345 为 77348)并保存。据我所知

$cookie_file_path=$path."/cookies/shipping-cookie".$unique; $handle = fopen($cookie_file_path, "r+"); $cookie_file_path = str_replace("12345", "77348", $cookie_file_path);

fclose($句柄);

但是它似乎不起作用....我将不胜感激!

4

4 回答 4

8

在您的代码中,您无法访问文件的内容。如果您使用的是 PHP 5,则可以使用如下内容:

$cookie_file_path = $path . '/cookies/shipping-cookie' . $unique;
$content = file_get_contents($cookie_file_path);
$content = str_replace('12345', '77348', $content);
file_put_contents($cookie_file_path, $content);

如果您使用的是 PHP 4,则需要结合使用 fopen()、fwrite() 和 fclose() 以获得与 file_put_contents() 相同的效果。但是,这应该会给您一个良好的开端。

于 2010-07-08T02:04:07.980 回答
1

您正在替换文件名,而不是内容。如果它是一个小文件,您可以使用file_get_contentsandfile_put_contents代替。

$cookie_file_path=$path."/cookies/shipping-cookie".$unique;
$contents = file_get_contents($cookie_file_path);
file_put_contents($cookie_file_path, str_replace("12345", "77348", $contents));
于 2010-07-08T02:01:32.547 回答
1

您需要为要保存的文件打开一个新的文件句柄,然后读取第一个文件的内容,应用翻译,然后将其保存到第二个文件句柄:

$cookie_file_path=$path."/cookies/shipping-cookie".$unique;

# open the READ file handle
$in_file = fopen($cookie_file_path, 'r');

# read the contents in
$file_contents = fgets($in_file, filesize($cookie_file_path));
# apply the translation
$file_contents = preg_replace('12345', '77348', $file_contents);
# we're done with this file; close it
fclose($in_file);

# open the WRITE file handle
$out_file = fopen($cookie_file_path, 'w');
# write the modified contents
fwrite($out_file, $file_contents);
# we're done with this file; close it
fclose($out_file);
于 2010-07-08T02:08:23.587 回答
0

您可以使用以下脚本。

$cookie_file_path = $path 。'/cookies/shipping-cookie' 。$独特; $content = file_get_contents($cookie_file_path); $content = str_replace('12345', '77348', $content); file_put_contents($cookie_file_path, $content);

谢谢

于 2010-07-08T05:06:10.807 回答