title: How To Delete The Top 100 Rows From a CSV File With PHP
body: <p>I have a php script running on a regular basis that processes the top 100 rows of a CSV file. When it is done I want it to delete the processed rows from the CSV file.</p>
  
  <p>I have tried the below code, but it does not delete anything. I am not sure the best way to state the condition in PHP and am not sure what to put for the $id. I set the number of rows at 5 for testing purposes. Likely have somy syntax wrong.</p>
  
  <p>Any suggestions? Tips?</p>
  
  <pre><code>    function delete_line($id)
  {
      if($id) 
      {
          $file_handle = fopen("file.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);
      }
  }
  
  $in = fopen( 'file.csv', 'r');
  $out = fopen( 'file.csv', 'w'); 
  // Check whether they opened
  
  while( $row = fgetcsv( $in, $cnt)){
  
    fputcsv( $out, $row);
  }
  
  fclose( $in); fclose( $out);
  </code></pre>
  
  <p>Whole script is here...</p>
  
  <pre><code>&lt;?php
  
  require_once('wp-config.php');
  
  
  
  $siteurl = get_site_url();
  
  
  
  //print_r($_FILES);
  
  //if($_FILES['file']['tmp_name']) {
  
    //$upload = ABSPATH . 'file.csv';
  
    //move_uploaded_file($_FILES['file']['tmp_name'], $upload);
  
  //}
  
  
  
  function clearer($str) {
  
    //$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
  
    $str = utf8_encode($str);
  
    $str = str_replace("’", "'", $str);
  
    $str = str_replace("–", "-", $str);
  
    return htmlspecialchars($str);
  
  }
  
  
  
  //file read
  
  if(file_exists("file.csv")) $csv_lines  = file("file.csv");
  
  if(is_array($csv_lines)) {
  
  
  
    $cnt = 5;
  
    for($i = 0; $i &lt; $cnt; $i++) {
  
      $line = $csv_lines[$i];
  
      $line = trim($line);
  
      $first_char = true;
  
      $col_num = 0;
  
      $length = strlen($line);
  
      for($b = 0; $b &lt; $length; $b++) {
  
        if($skip_char != true) {
  
          $process = true;
  
          if($first_char == true) {
  
            if($line[$b] == '"') {
  
              $terminator = '",';
  
              $process = false;
  
            }else
  
              $terminator = ',';
  
            $first_char = false;
  
          }
  
  
  
          if($line[$b] == '"'){
  
            $next_char = $line[$b + 1];
  
            if($next_char == '"')
  
              $skip_char = true;
  
            elseif($next_char == ',') {
  
              if($terminator == '",') {
  
                $first_char = true;
  
                $process = false;
  
                $skip_char = true;
  
              }
  
            }
  
          }
  
  
  
          if($process == true){
  
            if($line[$b] == ',') {
  
               if($terminator == ',') {
  
                  $first_char = true;
  
                  $process = false;
  
               }
  
            }
  
          }
  
  
  
          if($process == true)
  
            $column .= $line[$b];
  
  
  
          if($b == ($length - 1)) {
  
            $first_char = true;
  
          }
  
  
  
          if($first_char == true) {
  
            $values[$i][$col_num] = $column;
  
            $column = '';
  
            $col_num++;
  
          }
  
        }
  
        else
  
          $skip_char = false;
  
      }
  
    }
  
  
  
    $values = array_values($values);
  
    //print_r($values);
  
  
  
    /*************************************************/
  
  
  
    if(is_array($values)) {
  
      //file.csv read
  
      for($i = 0; $i &lt; count($values); $i++) {
  
        unset($post);
  
  
  
        //check duplicate
  
        //$wpdb-&gt;show_errors();
  
        $wpdb-&gt;query("SELECT `ID` FROM `" . $wpdb-&gt;prefix . "posts`
  
                              WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
  
          //echo $wpdb-&gt;num_rows;
  
  
  
        if($values[$i][0] != "Name" &amp;&amp; $values[$i][0] != "" &amp;&amp; $wpdb-&gt;num_rows == 0) {
  
          $post['name'] = clearer($values[$i][0]);
  
          $post['Address'] = clearer($values[$i][1]);
  
          $post['City'] = clearer($values[$i][2]);
  
          $post['Categories'] = $values[$i][3];
  
          $post['Tags'] = $values[$i][4];
  
          $post['Top_image'] = $values[$i][5];
  
          $post['Body_text'] = clearer($values[$i][6]);
  
  
  
          //details
  
          for($k = 7; $k &lt;= 56; $k++) {
  
            $values[$i][$k] != '' ? $post['details'] .= "&lt;em&gt;".clearer($values[$i][$k])."&lt;/em&gt;\r\n" : '';
  
          }
  
  
  
          //cats
  
          $categoryes = explode(";", $post['Categories']);
  
          foreach($categoryes AS $category_name) {
  
            $term = term_exists($category_name, 'category');
  
            if (is_array($term)) {
  
              //category exist
  
              $cats[] = $term['term_id'];
  
            }else{
  
              //add category
  
              wp_insert_term( $category_name, 'category' );
  
              $term = term_exists($category_name, 'category');
  
              $cats[] = $term['term_id'];
  
            }
  
          }
  
  
  
          //top image
  
          if($post['Top_image'] != "") {
  
            $im_name = md5($post['Top_image']).'.jpg';
  
  
  
            $im = @imagecreatefromjpeg($post['Top_image']); 
  
            if ($im) {
  
              imagejpeg($im, ABSPATH.'images/'.$im_name);
  
              $post['topimage'] = '&lt;img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" /&gt;';
  
            }
  
          }
  
  
  
          //bottom images
  
          for($k = 57; $k &lt;= 76; $k++) {
  
            if($values[$i][$k] != '') {
  
              $im_name = md5($values[$i][$k]).'.jpg';
  
  
  
              $im = @imagecreatefromjpeg($values[$i][$k]);
  
              if ($im) {
  
                imagejpeg($im, ABSPATH.'images/'.$im_name);
  
                $post['images'] .= '&lt;a href="'.$siteurl.'/images/'.$im_name.'"&gt;&lt;img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" /&gt;&lt;/a&gt;';
  
              }
  
            }
  
          }
  
  
  
          $post = array_map( 'stripslashes_deep', $post );
  
  
  
          //print_r($post);
  
  
  
          //post created
  
          $my_post = array (
  
             'post_title' =&gt; $post['name'],
  
             'post_content' =&gt; '
  
                &lt;em&gt;Address: '.$post['Address'].'&lt;/em&gt;
  
                '.$post['topimage'].'
  
                '.$post['Body_text'].'
  
                &lt;!--more--&gt;
  
                '.$post['details'].'
  
                '.$post['images'].'
  
             ',
  
             'post_status' =&gt; 'publish',
  
             'post_author' =&gt; 1,
  
             'post_category' =&gt; $cats
  
          );
  
          unset($cats);
  
  
  
          //add post
  
          //echo "ID:" .
  
          $postid = wp_insert_post($my_post); //post ID
  
  
  
          //tags
  
          wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
  
  
  
          echo $post['name']. ' - added. ';
  
  
  
          //google coords
  
          $address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
  
          $json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
  
          //print_r($json);
  
  
  
          if($json-&gt;status == "OK") {
  
            //нашло адрес
  
            $google['status'] = $json-&gt;status;
  
  
  
            $params = $json-&gt;results[0]-&gt;address_components;
  
            if(is_array($params)) {
  
              foreach($params AS $id =&gt; $p) {
  
                if($p-&gt;types[0] == 'locality') $google['locality_name'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'administrative_area_level_1') $google['admin_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'country') $google['country_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'postal_code') $google['postal_code'] = $p-&gt;short_name;
  
              }
  
            }
  
            $google['address'] = $json-&gt;results[0]-&gt;formatted_address;
  
            $google['location']['lat'] = $json-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat;
  
            $google['location']['lng'] = $json-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng;
  
  
  
            //print_r($params);
  
  
  
            //print_r($google);
  
  
  
            //insert into DB
  
            $insert_code = $wpdb-&gt;insert( $wpdb-&gt;prefix . 'geo_mashup_locations',
  
                                          array( 'lat' =&gt; $google['location']['lat'], 'lng' =&gt; $google['location']['lng'], 'address' =&gt; $google['address'],
  
                                                 'saved_name' =&gt; $post['name'], 'postal_code' =&gt; $google['postal_code'],
  
                                                 'country_code' =&gt; $google['country_code'], 'admin_code' =&gt; $google['admin_code'],
  
                                                 'sub_admin_code' =&gt; $google['sub_admin_code'], 'locality_name' =&gt; $google['locality_name'] ),
  
                                          array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
  
                                        );
  
            if($insert_code) {
  
              $google_code_id = $wpdb-&gt;insert_id;
  
              $geo_date = date( 'Y-m-d H:i:s' );
  
              $wpdb-&gt;insert(
  
                $wpdb-&gt;prefix . 'geo_mashup_location_relationships',
  
                array( 'object_name' =&gt; 'post', 'object_id' =&gt; $postid, 'location_id' =&gt; $google_code_id, 'geo_date' =&gt; $geo_date ),
  
                array( '%s', '%s', '%s', '%s' )
  
              );
  
            }else{
  
              //can't insert data
  
            }
  
  
  
            echo ' address added.&lt;br /&gt;';
  
  
  
          }else{
  
            //echo $json-&gt;status;
  
          }
  
  
  
        }
  
      } //$values end (for)
  
    }
  
  }else{
  
    //not found file.csv
  
    echo 'not found file.csv';
  
  }
  
  function delete_line($id)
  {
      if($id) 
      {
          $file_handle = fopen("file.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);
      }
  }
  
  $in = fopen( 'file.csv', 'r');
  $out = fopen( 'file.csv', 'w'); 
  // Check whether they opened
  
  while( $row = fgetcsv( $in, $cnt)){
  
    fputcsv( $out, $row);
  }
  
  fclose( $in); fclose( $out);
  
  ?&gt;
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>I tried one of the answer codes and got a server error. Code below, thoughts?</p>
  
  <pre><code>&lt;?php
  
  require_once('wp-config.php');
  
  
  
  $siteurl = get_site_url();
  
  
  
  //print_r($_FILES);
  
  //if($_FILES['file']['tmp_name']) {
  
    //$upload = ABSPATH . 'file.csv';
  
    //move_uploaded_file($_FILES['file']['tmp_name'], $upload);
  
  //}
  
  
  
  function clearer($str) {
  
    //$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
  
    $str = utf8_encode($str);
  
    $str = str_replace("’", "'", $str);
  
    $str = str_replace("–", "-", $str);
  
    return htmlspecialchars($str);
  
  }
  
  
  
  //file read
  
  if(file_exists("file.csv")) $csv_lines  = file("file.csv");
  
  if(is_array($csv_lines)) {
  
  
  
    $cnt = 5;
  
    for($i = 0; $i &lt; $cnt; $i++) {
  
      $line = $csv_lines[$i];
  
      $line = trim($line);
  
      $first_char = true;
  
      $col_num = 0;
  
      $length = strlen($line);
  
      for($b = 0; $b &lt; $length; $b++) {
  
        if($skip_char != true) {
  
          $process = true;
  
          if($first_char == true) {
  
            if($line[$b] == '"') {
  
              $terminator = '",';
  
              $process = false;
  
            }else
  
              $terminator = ',';
  
            $first_char = false;
  
          }
  
  
  
          if($line[$b] == '"'){
  
            $next_char = $line[$b + 1];
  
            if($next_char == '"')
  
              $skip_char = true;
  
            elseif($next_char == ',') {
  
              if($terminator == '",') {
  
                $first_char = true;
  
                $process = false;
  
                $skip_char = true;
  
              }
  
            }
  
          }
  
  
  
          if($process == true){
  
            if($line[$b] == ',') {
  
               if($terminator == ',') {
  
                  $first_char = true;
  
                  $process = false;
  
               }
  
            }
  
          }
  
  
  
          if($process == true)
  
            $column .= $line[$b];
  
  
  
          if($b == ($length - 1)) {
  
            $first_char = true;
  
          }
  
  
  
          if($first_char == true) {
  
            $values[$i][$col_num] = $column;
  
            $column = '';
  
            $col_num++;
  
          }
  
        }
  
        else
  
          $skip_char = false;
  
      }
  
    }
  
  
  
    $values = array_values($values);
  
    //print_r($values);
  
  
  
    /*************************************************/
  
  
  
    if(is_array($values)) {
  
      //file.csv read
  
      for($i = 0; $i &lt; count($values); $i++) {
  
        unset($post);
  
  
  
        //check duplicate
  
        //$wpdb-&gt;show_errors();
  
        $wpdb-&gt;query("SELECT `ID` FROM `" . $wpdb-&gt;prefix . "posts`
  
                              WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
  
          //echo $wpdb-&gt;num_rows;
  
  
  
        if($values[$i][0] != "Name" &amp;&amp; $values[$i][0] != "" &amp;&amp; $wpdb-&gt;num_rows == 0) {
  
          $post['name'] = clearer($values[$i][0]);
  
          $post['Address'] = clearer($values[$i][1]);
  
          $post['City'] = clearer($values[$i][2]);
  
          $post['Categories'] = $values[$i][3];
  
          $post['Tags'] = $values[$i][4];
  
          $post['Top_image'] = $values[$i][5];
  
          $post['Body_text'] = clearer($values[$i][6]);
  
  
  
          //details
  
          for($k = 7; $k &lt;= 56; $k++) {
  
            $values[$i][$k] != '' ? $post['details'] .= "&lt;em&gt;".clearer($values[$i][$k])."&lt;/em&gt;\r\n" : '';
  
          }
  
  
  
          //cats
  
          $categoryes = explode(";", $post['Categories']);
  
          foreach($categoryes AS $category_name) {
  
            $term = term_exists($category_name, 'category');
  
            if (is_array($term)) {
  
              //category exist
  
              $cats[] = $term['term_id'];
  
            }else{
  
              //add category
  
              wp_insert_term( $category_name, 'category' );
  
              $term = term_exists($category_name, 'category');
  
              $cats[] = $term['term_id'];
  
            }
  
          }
  
  
  
          //top image
  
          if($post['Top_image'] != "") {
  
            $im_name = md5($post['Top_image']).'.jpg';
  
  
  
            $im = @imagecreatefromjpeg($post['Top_image']); 
  
            if ($im) {
  
              imagejpeg($im, ABSPATH.'images/'.$im_name);
  
              $post['topimage'] = '&lt;img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" /&gt;';
  
            }
  
          }
  
  
  
          //bottom images
  
          for($k = 57; $k &lt;= 76; $k++) {
  
            if($values[$i][$k] != '') {
  
              $im_name = md5($values[$i][$k]).'.jpg';
  
  
  
              $im = @imagecreatefromjpeg($values[$i][$k]);
  
              if ($im) {
  
                imagejpeg($im, ABSPATH.'images/'.$im_name);
  
                $post['images'] .= '&lt;a href="'.$siteurl.'/images/'.$im_name.'"&gt;&lt;img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" /&gt;&lt;/a&gt;';
  
              }
  
            }
  
          }
  
  
  
          $post = array_map( 'stripslashes_deep', $post );
  
  
  
          //print_r($post);
  
  
  
          //post created
  
          $my_post = array (
  
             'post_title' =&gt; $post['name'],
  
             'post_content' =&gt; '
  
                &lt;em&gt;Address: '.$post['Address'].'&lt;/em&gt;
  
                '.$post['topimage'].'
  
                '.$post['Body_text'].'
  
                &lt;!--more--&gt;
  
                '.$post['details'].'
  
                '.$post['images'].'
  
             ',
  
             'post_status' =&gt; 'publish',
  
             'post_author' =&gt; 1,
  
             'post_category' =&gt; $cats
  
          );
  
          unset($cats);
  
  
  
          //add post
  
          //echo "ID:" .
  
          $postid = wp_insert_post($my_post); //post ID
  
  
  
          //tags
  
          wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
  
  
  
          echo $post['name']. ' - added. ';
  
  
  
          //google coords
  
          $address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
  
          $json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
  
          //print_r($json);
  
  
  
          if($json-&gt;status == "OK") {
  
            //нашло адрес
  
            $google['status'] = $json-&gt;status;
  
  
  
            $params = $json-&gt;results[0]-&gt;address_components;
  
            if(is_array($params)) {
  
              foreach($params AS $id =&gt; $p) {
  
                if($p-&gt;types[0] == 'locality') $google['locality_name'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'administrative_area_level_1') $google['admin_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'country') $google['country_code'] = $p-&gt;short_name;
  
                if($p-&gt;types[0] == 'postal_code') $google['postal_code'] = $p-&gt;short_name;
  
              }
  
            }
  
            $google['address'] = $json-&gt;results[0]-&gt;formatted_address;
  
            $google['location']['lat'] = $json-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat;
  
            $google['location']['lng'] = $json-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng;
  
  
  
            //print_r($params);
  
  
  
            //print_r($google);
  
  
  
            //insert into DB
  
            $insert_code = $wpdb-&gt;insert( $wpdb-&gt;prefix . 'geo_mashup_locations',
  
                                          array( 'lat' =&gt; $google['location']['lat'], 'lng' =&gt; $google['location']['lng'], 'address' =&gt; $google['address'],
  
                                                 'saved_name' =&gt; $post['name'], 'postal_code' =&gt; $google['postal_code'],
  
                                                 'country_code' =&gt; $google['country_code'], 'admin_code' =&gt; $google['admin_code'],
  
                                                 'sub_admin_code' =&gt; $google['sub_admin_code'], 'locality_name' =&gt; $google['locality_name'] ),
  
                                          array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
  
                                        );
  
            if($insert_code) {
  
              $google_code_id = $wpdb-&gt;insert_id;
  
              $geo_date = date( 'Y-m-d H:i:s' );
  
              $wpdb-&gt;insert(
  
                $wpdb-&gt;prefix . 'geo_mashup_location_relationships',
  
                array( 'object_name' =&gt; 'post', 'object_id' =&gt; $postid, 'location_id' =&gt; $google_code_id, 'geo_date' =&gt; $geo_date ),
  
                array( '%s', '%s', '%s', '%s' )
  
              );
  
            }else{
  
              //can't insert data
  
            }
  
  
  
            echo ' address added.&lt;br /&gt;';
  
  
  
          }else{
  
            //echo $json-&gt;status;
  
          }
  
  
  
        }
  
      } //$values end (for)
  
    }
  
  }else{
  
    //not found file.csv
  
    echo 'not found file.csv';
  
  }
  
  
  function csv_delete_rows($filename='file.csv', $startrow=1, $endrow=5, $inner=false) {
  $status = 0;
  //check if file exists
  if (file_exists($filename)) {
      //end execution for invalid startrow or endrow
      if ($startrow &lt; 0 || $endrow &lt; 0 || $startrow &gt; 0 &amp;&amp; $endrow &gt; 0 &amp;&amp; $startrow &gt; $endrow) {
          die('Invalid startrow or endrow value');
      }
      $updatedcsv = array();
      $count = 0;
      //open file to read contents
      $fp = fopen($filename, "r");
      //loop to read through csv contents
      while ($csvcontents = fgetcsv($fp)) {
          $count++;
          if ($startrow &gt; 0 &amp;&amp; $endrow &gt; 0) {
              //delete rows inside startrow and endrow
              if ($inner) {
                  $status = 1;
                  if ($count &gt;= $startrow &amp;&amp; $count &lt;= $endrow)
                      continue;
                  array_push($updatedcsv, implode(',', $csvcontents));
              }
              //delete rows outside startrow and endrow
              else {
                  $status = 2;
                  if ($count &lt; $startrow || $count &gt; $endrow)
                      continue;
                  array_push($updatedcsv, implode(',', $csvcontents));
              }
          }
          else if ($startrow == 0 &amp;&amp; $endrow &gt; 0) {
              $status = 3;
              if ($count &lt;= $endrow)
                  continue;
              array_push($updatedcsv, implode(',', $csvcontents));
          }
          else if ($endrow == 0 &amp;&amp; $startrow &gt; 0) {
              $status = 4;
              if ($count &gt;= $startrow)
                  continue;
              array_push($updatedcsv, implode(',', $csvcontents));
          }
          else if ($startrow == 0 &amp;&amp; $endrow == 0) {
              $status = 5;
          } else {
              $status = 6;
          }
      }//end while
      if ($status &lt; 5) {
          $finalcsvfile = implode("\n", $updatedcsv);
          fclose($fp);
          $fp = fopen($filename, "w");
          fwrite($fp, $finalcsvfile);
      }
      fclose($fp);
      return $status;
  } else {
      die('File does not exist');
  }
  }
  
  
  ?&gt;
  
  &lt;html&gt;
  
  &lt;body&gt;
  
  &lt;form enctype="multipart/form-data" method="post"&gt;
  
   CSV: &lt;input name="file" type="file" /&gt;
  
   &lt;input type="submit" value="Send File" /&gt;
  
  &lt;/form&gt;
  
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>