質問

4列の.csvファイルがあります。最初の列のIDと同じ行を削除する最も簡単な方法は何ですか?これが私が立ち往生したところです:

if($_GET['id']) {
    $id = $_GET['id'];
    $file_handle = fopen("testimonials.csv", "rw");

    while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);    
        if ($id == $line_of_text[0]) {
            // remove row
        }
    }
    fclose($file_handle);
}

残念ながら、データベースは選択肢ではありませんでした。

役に立ちましたか?

解決

$id = $_GET['id'];
if($id) {
    $file_handle = fopen("testimonials.csv", "w+");
    $myCsv = array();
    while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);    
        if ($id != $line_of_text[0]) {
            fputcsv($file_handle, $line_of_text);
        }
    }
    fclose($file_handle);
}

他のヒント

$table = fopen('table.csv','r');
$temp_table = fopen('table_temp.csv','w');

$id = 'something' // the name of the column you're looking for

while (($data = fgetcsv($table, 1000)) !== FALSE){
    if(reset($data) == $id){ // this is if you need the first column in a row
        continue;
    }
    fputcsv($temp_table,$data);
}
fclose($table);
fclose($temp_table);
rename('table_temp.csv','table.csv');

私は最近、ニュースレターのunsubscriptionのために同様のことをしました、私のコードは次のとおりです。

$signupsFile = 'newsletters/signups.csv';
$signupsTempFile = 'newsletters/signups_temp.csv';
$GLOBALS["signupsFile"] = $signupsFile;
$GLOBALS["signupsTempFile"] = $signupsTempFile;


function removeEmail($email){
    $removed = false;
    $fptemp = fopen($GLOBALS["signupsTempFile"], "a+");
    if (($handle = fopen($GLOBALS["signupsFile"], "r")) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
        if ($email != $data[0] ){
            $list = array($data);
            fputcsv($fptemp, $list);
            $removed = true;
        }
    }
    fclose($handle);
    fclose($fptemp);
    unlink($GLOBALS["signupsFile"]);
    rename($GLOBALS["signupsTempFile"], $GLOBALS["signupsFile"]);
    return $removed;
}

これにより、メモリエラーを回避するために、CSVラインごとにCSVラインを書き出すTEMPファイル方法を使用します。次に、新しいファイルが作成されると、元のファイルが削除され、Tempファイルの名前が変更されます。

このコードを変更して、電子メールアドレスの代わりにIDを探すことができます。

$id = $_GET['id'];  
$fptemp = fopen('testimonials-temp.csv', "a+");
if (($handle = fopen('testimonials.csv', "r")) !== FALSE) {
    while (($id= fgetcsv($handle)) !== FALSE) {
    if ($id != $data[0] ){
        $list = array($data);
        fputcsv($fptemp, $list);
    }
}
fclose($handle);
fclose($fptemp);
unlink('testimonials.csv');
rename('testimonials-temp.csv','testimonials.csv');

できるよ:

$new = '';
while (!feof($file_handle))
{
    $line_of_text = fgetcsv($file_handle, 1024);    
    if ($id != $line_of_text[0])
    {
         $new .= implode(',',$line_of_text) . PHP_EOL;
    }
}

基本的に実行しているラインを実行して、IDが行うかどうかを確認します いいえ GETパラメーターで送信されたIDと一致します。 いいえ 次に、新しいコンテナ /変数にラインを書き込みます。

そして、書き直します $new ファイルの値、これは正常に動作するはずです:

  • ファイルの大きさ
  • CSVヘッダーはオンラインにありますか? 0?
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top