skip to Main Content

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)’

2

Answers


  1. The error you’re seeing is because you’re passing a string to the fgetcsv function, but it expects a file resource. You can use the fopen function to open the file and get a file resource.

    public function actionReadfile(){
        $file = fopen('ContactList.csv', 'r'); 
    
        if($file == null){
            return;
        } else {
            $file_arr = [];
            while (($data = fgetcsv($file)) !== false) {
                $file_arr[$data[1]] = $data[0]; // Assuming phone number is in the first column and name is in the second
            }
            fclose($file); 
    
            Yii::$app->response->format = Response::FORMAT_JSON;
            return $file_arr;     
        }
    }
    
    Login or Signup to reply.
  2. 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); 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search