douba1498 2016-04-11 14:55
浏览 41

使用系统调用在php中写入和读取文件是否合适?

I need to keep a 20k to 30k file register with a simple key:value per line. I need to keep it in a file , since other instance also will use it. Then I will need to find an especific key to get its value and also write a key:value in the file. I was wondering wich of the following methods are faster / better or considered as good practice.

In order to write to file, I know about three ways to do it: first:

$fh = fopen('myfile.txt', 'a') or die("can't open file");
fwrite($fh, 'key:value');
fclose($fh);

second or with file_put_contents

file_put_contents('myfile.txt','key:value',FILE_APPEND);

and third using a system call.

exec("echo key:value >> myfile.txt");

And also, in order to read a file and find a line a can do: Using file_get_contents

$filename = 'info.txt';
$contents = file_get_contents($filename);
foreach($contents as $line) {
$pos = strpos($line, $key);
}

Using file

$filename = 'info.txt';
$contents = file($filename);
foreach($contents as $line) {
$pos = strpos($line, $key);
}

And with a system call:

exec("grep $key | wc -l",$result);
  • 写回答

1条回答 默认 最新

  • dongyue7796 2016-04-11 15:07
    关注

    I guess you already considered using a database? Because otherwise you are reinventing the wheel. A database has all the advantages with fast-seeking and row-level locking.

    If you are using a file, you have to build this by yourself.

    I strongly advice to switch to some kind of database.

    BTW, you don't mention if you are replacing values or just appending to the file.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀