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
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.
You got this error because
fgetcsv
requires an opened file, to be parsed.Cf: official documentation.
Your code will look better this way: