开发者

php fopen , str_replace

I need to open a file , replace some content( 12345 with 77348) and save it. As far I have

$cookie_file_path=$path."/cookies/shippi开发者_JAVA百科ng-cookie".$unique; $handle = fopen($cookie_file_path, "r+"); $cookie_file_path = str_replace("12345", "77348", $cookie_file_path);

fclose($handle);

However it doesn't seem to work .... I would appreciate any help!


Nowhere in your code do you access the content of your file. If you are using PHP 5, you can use something like the following:

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

If you are on PHP 4, you will need to use a combination of fopen(), fwrite(), and fclose() in order to get the same effect as file_put_contents(). However, this should give you a good start.


You're doing the replace on the filename, not the contents. If it's a small file, you can use file_get_contents and file_put_contents instead.

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


You will need to open a new file handle to the file you want to save, then read the contents of the first file, apply the translation, then save it to the second file handle:

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


You can use below script.

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

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜