PHP parsing csv file

Source: Internet
Author: User
Tags explode parse csv file

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.