且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用php替换文本文件中的特定行?

更新时间:2023-01-15 18:05:57

似乎您有csv格式的文件. PHP可以使用fgetcsv() http://php.net/manual/de/function处理此问题.fgetcsv.php

It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php

if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
    $data = fgetcsv($handle, 1000, '|')
    /* manipulate $data array here */
}

fclose($handle);

这样您将获得一个可以操纵的数组.之后,您可以使用fputcsv http://www.php.net/保存文件manual/de/function.fputcsv.php

So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php

$fp = fopen('contacts.tmp', 'w');

foreach ($data as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

好吧,在阿萨德发表评论后,还有另一个简单的答案.只需在Append模式下打开文件 http://de3.php.net/manual /en/function.fopen.php :

Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :

$writing = fopen('contacts.tmp', 'a');