2010-07-08 54 views
1

我需要打開一個文件,替換一些內容(12345與77348)並保存。到目前爲止,我有php fopen,str_replace

$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($handle);

但它似乎並沒有工作....我將不勝感激任何幫助!

+0

對不起,我沒有時間發佈了詳細的解答,但你告訴str_replace函數在$ cookie_file_path,而不是文件的實際內容與「77348」來代替「12345」。您需要將文件內容讀入緩衝區並替換爲THAT,然後重寫文件內容。 – jaywon 2010-07-08 02:02:08

+0

你可能也想在那裏有一個fwrite。 – JAL 2010-07-08 02:05:18

回答

5

在代碼中沒有任何地方訪問文件的內容。如果你正在使用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()相同的效果。不過,這應該會給你一個好的開始。

1

你正在替換文件名,而不是內容。如果它是一個小文件,則可以使用file_get_contentsfile_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)); 
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); 
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);

感謝