PHP文本操作类概述与效率建议
这里分享一个用于处理文本文件的简易PHP类。
这是早期编写的代码,虽然在实际项目中较少使用(因为数据库通常更优),但作为文本处理的示例仍有参考价值。
该类假设数据按行存储,每行以\n结尾。需要注意的是,输入的数据必须确保以"\n"结束。在处理文本时,效率是关键考量因素。例如,若要更新文件的第2、3、4行,直接调用多次update方法并非最优解。
低效的做法是循环调用更新函数:for($i=2;$i<=4;$i++)$this->update($file,$i,$msg);
更高效的方式是先一次性读取所有数据到数组中:$data=$this->read($file);
然后在内存中修改指定索引的值:for($i=2;$i<=4;$i++)$data[$i]=$msg;
最后将修改后的数组整体写回文件:$this->write($file,$data);
class text{
var $key="
<?die ;?>"; //数据保护字段
var $keylen; //记录数据保护的长度
function text() //类的构造函数
{
$this->keylen=strlen($this->lkeylen); //获取保护数据的长度
}
function read($file) //读取文件,返回数组格式的数据
{
if(file_exists($file)):
$data=@file($file); //读取文件内容为数组
$data[0]=substr($data[0],$this->keylen); //去除第一行的保护头部
return $a; //注意:原代码此处变量名不一致,应为$data
endif;
}
function write($file,$data=array()) //写入文件,参数为数组
{
if($fp=fopen($file,"w")):
flock($fp,3); //对文件进行锁定
fwrite($fp,$this->key); //写入保护头部
foeach($data as $v)fwrite($fp,$v); //遍历数组写入内容,原代码拼写有误应为foreach
return true;
endif;
}
function add($file,$msg)
//向文件末尾添加数据,若文件不存在则自动创建
{
$a=$this->read($file); //无论文件是否存在都尝试读取
$a[]=$msg; //在数组末尾追加新消息
return $this->write($file,$a); //写回文件
}
function insert($file,$n,$msg) //在第$n行前插入数据
{
if($a=$this->read($file)):
$a[$n]=$msg.$a[$n]; //将新消息与原行内容拼接
return true;
endif;
}
function updata($file,$n,$msg) //更新第$n行的数据
{
if($a=$this->read($file)):
$a[$n]=$msg; //替换指定索引的内容
return true;
endif
}
function del($file,$n) //删除第$n行的数据
{
return $this->updata($file,$n,""); //通过设置为空字符串来实现删除效果
}
}