In Php trying to read a csv file to display in array

42 views Asked by At

I have a csv file with phone column and name column . I want to fetch the phone number as value and name as key .Its a loong file . Here is my code that I tried;

   public function actionReadfile(){
      $file=('ContactList.csv'.'r'); 
      if($file==Null){
       return;
    }else{
        
        while (($data = fgetcsv($file)) !== false) {
            $file_arr[] = $data;
        }
        foreach($data as $value){
            array_push($value->$file_arr);
            Yii::$app->response->format=Response::FORMAT_JSON;
            return $file_arr;     
      }
      fclose($file); 
}

}

I tried using fgetcsv($file) name of the file but im getting error.'Argument '1' passed to fgetcsv() is expected to be of type resource, string givenPHP(PHP0406)'

1

There are 1 answers

0
Eternal Learner On

You got this error because fgetcsv requires an opened file, to be parsed. Cf: official documentation.

Your code will look better this way:

public function actionReadfile() {
    $file = fopen("ContactList.csv", "r");
    if (false === $file) {
        return;
    }
    
    while (($data = fgetcsv($file)) !== FALSE) {
        //... bla bla bla
    }
    fclose($file); 
}