[英]PHP - read from flatfile, remove line and write back to flat file
希望得到一些帮助
我有一个txt文件,其中包含以下内容:
1234|dog|apartment|two
1234|cat|apartment|one
1234|dog|house|two
1234|dog|apartment|three
我想删除动物是“狗”住在“房子”里的条目
<?php
if (isset($_POST['delete_entry]))
{
//identifies the file
$file = "db.txt";
//opens the file to read
@$fpo = fopen($file, 'r');
//while we have not reached the end of the file
while(!feof($fpo))
{
//read each line of the file into an array called animal
$animal[] = fgets($fpo);
}
//close the file
fclose($fpo);
//iterate through the array
foreach ($animal as $a)
{
if the string contains dog and apartment
if ((stripos ($a, 'dog']))&&(stripos ($a, 'house')))
{
//dont do anything
}
else
{
//otherwise print out the string
echo $a.'<br/>';
}
}
}
?>
这样就可以成功打印出阵列,而不会出现'dog'和'house'出现的条目。 我需要把它写回平面文件,但遇到困难。
我尝试了各种选项,包括在找到每个条目时立即写回文件。
Warning: feof() expects parameter 1 to be resource, boolean given in
Warning: fwrite(): 9 is not a valid stream resource in
Warning: fclose(): 9 is not a valid stream resource in
这些是我遇到的错误之一。 现在从我对数组的理解,
- 当我通过这个名为animal的数组时,
- 它检查索引[0]的两个条件和
- 如果未找到该条目,则分配给$ a。
- 然后它从索引[1]开始经过数组,
- 等等。
每次将新值分配给$ a。
我认为每次出现它都可以将文件打印到文件中,但这是我在上面得到fwrite和fclose错误的地方,并且不知道如何解决这个问题。
我仍然需要做一些我需要用房子替换'公寓',一个特别选择的条目,但一旦我整理了“删除”就会到达那里
我不需要代码,也许只是一个可能对我有帮助的逻辑流程。
谢谢
这个步骤怎么样:
为了节省一些时间,只有在从文件中读取验证规则时才能将数据存储在数组中,并且在读取文件末尾后,您已准备好将数据写回文件。
您可以做的是在读取模式下打开源文件,在写入模式下打开临时文件。 当您从“in”文件中读取内容时,您会在“out”文件中写入行。 处理并关闭“in”文件时,将“out”重命名为“in”。 这样您就不必担心内存限制。
处理每一行时,如果你拆分'|'会更好,所以你知道第二个元素包含一个动物名称而第三个元素包含一个外壳名称。 谁知道一只猫是否住在狗窝里。
<?php
$fileName = 'db.txt';
$data = @file($fileName);
$id = 0;
$animal = "";
$type = "";
$number = 0;
$excludeAnimal = array("dog");
$excludeHouseType = array("house");
foreach($data as $row) {
list($id,$animal,$type,$number) = explode("|",$row);
if(in_array($animal,$excludeAnimal) && in_array($type,$excludeHouseType))
continue
/* ... code ... */
}
?>
虽然这不能回答你原来的问题,但我想分享一下我的想法。
我很确定这会将你的整个脚本分成三行:
$file = file_get_contents( 'db.txt');
$result = preg_replace('/^\d+\|dog\|house\|\w+$/m', '', $file);
file_put_contents( 'db.txt', $result);
它使用正则表达式来替换dog|house
的行,然后将文件写回。
$array_1
。 $array_2
。 $newarray
连接2个数组,重写为原始flatfile。 简单!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.