I created a feature to check if a spreadsheet has the correct layout, before uploading it to the database, it works perfectly for spreadsheets that are outside the requested standard. The problem is, when I upload it to check one that has the correct layout, it gives the same exception message as if it were wrong.

This was the function I created to do the validation:

private function validateFields(string $file): self
        $fh = fopen($file, 'r');
        $header = fgetcsv($fh);

        foreach ($header as $value) {
            if (!in_array(strtoupper($value),
             self::MAP) || count(self::MAP) != count($header)) {
                 throw new \Exception('Invalid archive layout.');
        return $this;

And here is where i'm calling this function with a try catch for this exception message:

public function execute()
        $files = $this->getRequest()->getFiles('files');

        $resultRedirect = $this->resultRedirectFactory->create();

        if (empty($files['tmp_name'])) {
            $this->messageManager->addWarningMessage(__('No files were uploaded.'));
            return $resultRedirect;

        try {
            $file = $this->setExtensionInTemporaryFile($files['tmp_name'], $files['name']);

            $fileData = $this->file->readFile($file, self::SPREADSHEET_TAB);


            $this->messageManager->addSuccessMessage(__('Customer segment attributes save successfuly.'));
        } catch (\InvalidArgumentException $e) {
            $this->messageManager->addErrorMessage(__('Make sure the file extension refers to a csv.'));
        } catch (CouldNotSaveException $e) {
                __('One or more lines do not contain correct values. Check and try again.')
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('The csv layout is invalid. Check and try again.')
        return $resultRedirect;
  • Why is this like this $this->validateFields('$file'); why not like this $this->validateFields($file); Mar 16, 2021 at 14:41

1 Answer 1


Check this, maybe it helps:

Important! We recommend that you use a program that supports UTF-8 encoding, such as Notepad++ or OpenOffice Calc, to edit CSV files. Microsoft Excel inserts additional characters into the column header of the CSV file, which can prevent the data from being imported back into Magento. If you work on the Mac, you can save your data in the CSV (Windows) format.

Reference: https://docs.magento.com/user-guide/system/data-csv.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.