开发者

Change file contents

We have a script, /scripts/ourscript.php and a file, /texts/elvis.txt.

How can we change contents of this file, when we run ourscript开发者_开发问答.php?


Use file_put_contents() method to set the contents of a file.

If you need just to save new data, you can do:

$elvis = 'Contents here';
$fileName = '..' . PATH_SEPARATOR . 'texts' . PATH_SEPARATOR . 'elvis.txt';
if (file_put_contents($fileName, $elvis) === false)
{
    // Handle error here.
}

If, instead of saving data, you need to change existing data, do:

$fileName = '..' . PATH_SEPARATOR . 'texts' . PATH_SEPARATOR . 'elvis.txt';
$elvis = file_get_contents($fileName);
// Do changes to $elvis here.
if (file_put_contents($fileName, $elvis) === false)
{
    // Handle error here.
}

Finally, if you need to append something new to existing contents, use:

$elvis = PHP_EOL . 'Contents to append to existing stuff here';
$fileName = '..' . PATH_SEPARATOR . 'texts' . PATH_SEPARATOR . 'elvis.txt';

// Noticed FILE_APPEND as third argument?
if (file_put_contents($fileName, $elvis, FILE_APPEND) === false)
{
    // Handle error here.
}


While MainMa has given you a direct answer, I'll point you to:
http://php.net/manual/en/function.file.php

Since it seems that you might have more of these questions, which could have been easily answered by looking at the documentation.

Also by figuring things out with the help of the documentation you'll learn how to solve such problems on your own, you know independence is a nice thing to have :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜