在我的wamp服务器中,我有一个每秒更新csv文件的脚本。我想从csv文件中删除行,我有这个代码(从这里:如何用PHP删除csv文件中的前100行):
$input = explode("'n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first 100 elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, 100);
file_put_contents("out.csv", implode("'n", $output));
问题发生时,我试图运行上面的代码,我得到:
"打开流权限被拒绝"
这个问题是因为文件一直在更新。我怎么知道的?我做了一个csv文件的拷贝(这个文件的内容根本没有更新),它成功了。
为什么我需要这个?
因为文件正在增长,我必须从他那里删除行..如果我不这样做,我得到:"PHP致命错误:允许的内存大小********字节耗尽(试图分配71字节)在/var/www/*******.php在第54行,"即使我写ini_set("memory_limit", "-1");
我提醒你-这是wamp服务器!
任何想法?
谢谢!
这不是你问的。但在我看来,你现有的计划是错误的。然后你在寻找一个愚蠢的解决方案来解决它。你有多任务的问题,这不是一个快速的过程。每次这样做都可能会丢失几行代码。
正确的方法是创建一个文件夹,例如LOGS。
然后放入一个文件名为YYYYMMDD.CSV的文件。每天换一个名字。并删除所有超过7天的内容
$input = explode("'n", file_get_contents("file.csv")); foreach ($input as $line) { // process all lines. } // This function removes first 100 elements. // More info: // http://php.net/manual/en/function.array-slice.php $output = array_slice($input, 100); file_put_contents("out.csv", implode("'n", $output));
问题发生时,我试图运行上面的代码,我得到:
"打开流权限被拒绝"
这里有三种情况你不能修改文件。
- 文件正在使用(被其他进程锁定).
- 文件没有权限(R/W)。或者文件不属于你正在使用的用户/组,在php的情况下,它是(www-data)。
- 文件不存在
1)如果文件已经在使用,你不能修改它,但你可以尝试其他的*
A RACE CONDITION *
可以使它发生:
# RACE CONDITION LOOP
# The only way you have here is to setup a RC loop to check if/when the file can be written.
$Path = dirname ( __FILE__ ) . "path_to_your_file/out.csv";
$tries = 99; // Any number of tries you want.
for ( $i = 1; $i < $tries; $i++ )
{
$output = array_slice ( $input, 100 );
{
if ( @file_put_contents ( $Path , implode ( "'n", $output ) ) )
{
echo "Content Added!"."<br>";
$i = $tries;
}
else
{
echo "Content Cannot be Added!"."<br>";
}
}
ob_flush ( );
echo "We Have tried " . $i . " times to add content to the file"."<br>";
sleep ( 1 );
flush ( );
}
2)如果文件没有正确的权限,你可以在你的代码中设置它:
$Path = dirname ( __FILE__ ) . "path_to_your_file/out.csv";
$Mode = 0755; // permissions wanted
$Umsk = @umask( 0 );
@chmod ( $Path, $Mode );
@umask ( $Umsk );
3)如果文件不存在,你可以创建它,但首先要确保检查它是否存在:
# Make sure the file that contain this code have the right permissions, user/group .
# If not this cannot create the file and will not allow you execute the whole code .
$Path = dirname ( __FILE__ ) . "path_to_your_file/out.csv";
$Mode = 0755; // permissions wanted
$Check_File = file_exists ( $Path );
if ( $Check_File ) { $File_Exist = true; }
else { $File_Exist = false; }
if ( $File_Exist )
{
@touch ( $Path );
@chmod ( $Path, $Mode );
}
else
{
echo "File Already Exist";
}
我希望这能帮到你,如果没有,请说明到底是什么问题。
PS:对于内存限制错误,一些服务器和/或主机提供程序不允许在用户的php.ini或from php中设置此选项。你必须编辑PHP和apache的全局配置文件,如果你使用大量的数据作为数据库,也许mysql也可以,以允许内存限制的最大选择值