我有一个 csv 文件,其中包含电话列和姓名列。我想获取电话号码作为值,名称作为键。它是一个长文件。这是我尝试过的代码;
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);
}
}
我尝试使用 fgetcsv($file) 文件名,但出现错误。传递给 fgetcsv() 的参数 '1' 预计为资源类型,字符串给定 PHP(PHP0406)'
您看到的错误是因为您将字符串传递给 fgetcsv 函数,但它需要文件资源。您可以使用fopen函数打开文件并获取文件资源。
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;
}
}