1

If I try to import a csv file, all the empty rows also get imported.

I have a form which takes a csv file

Following is the form action code

$file = $_FILES['file']['tmp_name'];
$allowedExts = array("csv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if (!in_array($extension, $allowedExts)) {
        $this->session->set_flashdata('msg', 'Please upload a csv file format.');
    }
    else {
    $handle = fopen($file, "r");
    $c = 0;
    $flag = true;
    while(($filesop = fgetcsv($handle, 0, ",")) !== false)
    {
        if($flag) { $flag = false; continue; } //to skip the title row

        if($filesop != NULL ) {  //CONDITION TO CHECK EMPTY ROWS (DOES not work..)

       $data[] = array(
                'id'=>0, //uploader user id
                'field1' => (isset($filesop[14]) ? $filesop[14] : "" ),
                'field2' => (isset($filesop[15]) ? $filesop[15] : "" ),
                'field3' => (isset($filesop[1]) ? $filesop[1] : "" ),
                'field4' => (isset($filesop[13]) ? $filesop[13] : "" ),
                'field5' => (isset($filesop[6]) ? $filesop[6] : "" ),
                'field6' => (isset($filesop[2]) ? $filesop[2] : "" ),
                'field7' => (isset($filesop[5]) ? $filesop[5] : "" ),
                'field8' => (isset($filesop[3]) ? $filesop[3] : "" ),
                'field9' => (isset($filesop[4]) ? $filesop[4] : "" ),
            );
        }
    }
           echo "<pre>";
    print_r($data);
    exit;

Please help me fix , what can I do so that the empty rows do not get imported

6
  • also tried if(array( null ) != $filesop) condition, does not work What am i doing wrong please tell me i am not getting it Commented Dec 29, 2016 at 4:47
  • Try to replace $filesop != NULL by if(!empty($filesop)) Commented Dec 29, 2016 at 4:48
  • tried .. that too Commented Dec 29, 2016 at 4:49
  • I would say to try the if condition directly on one of your key as follow if(!empty($filesop[1])) can u show us a example of your CVS ? Commented Dec 29, 2016 at 4:54
  • use $empty_filesop = array_filter( array_map( 'trim', $filesop) ); if( !empty( $empty_filesop)){ ... } Commented Dec 29, 2016 at 5:00

2 Answers 2

2

I would use array_filter to remove empty elements from the array then check if anything is left.

while(($filesop = fgetcsv($handle, 0, ",")) !== false){

  $empty_filesop = array_filter( array_map('trim', $filesop));

  if( !empty( $empty_filesop ) ){

      .....
  }
}

Array map with trim, will trim the data to remove lines with empty space such as ,{space}, think of it like this:

  foreach( $empty_filesop as &$item ) 
     $item = trim( $item );

Also, be aware PHP treats several things as empty that you may not consider empty and will remove them with the standard array_filter, such as 0 as in ,0, or array( 0, 'blah' ) the element with a 0 would be removed. If you need more accuracy you can do something like this:

 $empty_filesop = array_filter(
        array_map('trim', $filesop),
        function( $item ){
            return strlen( $item ); //return the string length of $item ( 0 is false > 0 is true )
        }
 );

If you rely on the elements positions it will change if there are empty rows, so make a copy of it to check. For example use $empty_filesop that way you don't alter the actual row with the filter...

http://php.net/manual/en/function.array-filter.php

http://php.net/manual/en/function.array-map.php

http://php.net/manual/en/function.trim.php

For headers do it like this( I don't know the orignal keys ):

$headers = false;
$order = ['id'=>0, 'org3'=>'', 'org2'=>'', 'org1'=>''];
while(($filesop = fgetcsv($handle, 0, ",")) !== false)
{
    if(!$headers) { $headers = $filesop; continue; } 

    $empty_filesop = array_filter( array_map('trim', $filesop));

    if( !empty($empty_filesop)){
      //check for empty rows
      if( count( $headers ) == count($filesop) ) {  
       //check for rows with extra or missing delimiters.
        $data[] = array_replace( $order, array_combine( $headers, $filesop)); //combine with original headers, and replace the data in the 'order row' to re-order.
       }else{
           //row is missing or has extra delimiters.
       }
    }
}
Sign up to request clarification or add additional context in comments.

24 Comments

Thanks a lot!! array_filter with array_map worked. One more thing.. I have comma separated values in some of the rows in the csv file so fgetcsv($handle, 0, ",") does not import proper data in the table I Can use "\t" but for that ill have to save file in the text(tab delimited) format , I need a csv file only .. Can you please tell me how that can be done..
if they have commas in the text PHP should handle it fine, if they are quoted like "data with, comma", 1234, ... . fputcsv will do that by default, it actually quotes fields with spaces too like "field with spave", 1233, Its the $enclosure part in the fgetcsv function, default " is quote.
for that ill have to add double quotes in the csv file .. ?
Oh, and you don't need to do this fgetcsv($handle, 0, ",") you can just do fgetcsv($handle) those are the defaults.
Depends what you mean by add, where is the CSV come from.. Both Excel and PHP fputcsv should do that by default. If you open it in a text editor like Notepad++ it should look like this field,"field with space","field with, comma". PHP can even handle line returns as long as the field has quotes around it "data \n foo", If the fields are not quoted then there is a problem with how it was written.
|
0

Change

if ($filesop != null) 

To

if ($filesop !== array(null)) // note the triple equals

Look at the return values section of the docs: http://php.net/manual/en/function.fgetcsv.php

5 Comments

I tried printing $filesop in while loop I did not get null for empty rows instead i got an array as Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => ) Is there anything which is not proper in the code..
Are there any invisible characters in the array?
why m i not getting null for empty row.. can you please check my code
how do i check that bcs if I print the array it gives the array as in the above comment ..
@san - this is because your file has the delimiters in it for example ,,,, becomes array(0=>'', 1=>'',2=>'', ... ). So you have to remove the empty elements and then check, as in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.