Public Function Actionimport () {
Post request came in
$fileName = $_files[' file ' [' Name '];
$fileTmpName = $_files[' file ' [' Tmp_name '];
Determine if the uploaded file is selected
if (empty ($fileName)) {
$data [' message '] = "Please select the file to upload";
return $this->render ("Batch_add", $data);
}
Determine if the file you choose to upload is not in CSV format
if (Explode (".", $fileName) [1]! = "CSV") {
$data [' message '] = "Please select File Upload in csv format";
return $this->render ("Batch_add", $data);
}
Create an empty array, pre-release ImageUrl
$imageCollection = [];
Open the file you want to read
$handle = fopen ($fileTmpName, ' R ');
Parse CSV file
while (!feof ($handle)) {
Fgets method read by line
$result = fgets ($handle);
Determine if each row read has a value
if (!empty ($result)) {
$arrResult = Explode (",", $result);
$name = $arrResult [0];
$age = $arrResult [1];
$gender = $arrResult [2];
The original path of the picture
$imagePath = $arrResult [3];
The name of the picture
$image = basename ($imagePath);
$data [' message '] = Person::saveperson ($name, $age, $gender, $image);
if ($data [' message '] = = ' Add successful ') {
Place the URI of each picture in the array
Array_push ($imageCollection, $imagePath);
}
}
}
Close file stream
Fclose ($handle);
After you close the file stream before uploading the picture, note that streams and streams are not nested
if (!empty ($imageCollection)) {
foreach ($imageCollection as $value) {
Upload the picture to the server
Move_uploaded_file ($imagePath, DirName (__dir__). '/web/images/'. Date ("Ymd"). ' /'. $image);
}
}
return $this->render ("Batch_add", $data);
}
PHP parsing csv file