Read More
Read More
Menu Close

    Create Files Programmatically In Magento 2

    This article demonstrate how to create files like (image, pdf, xls, docx etc.) programmatically in Magento 2.

    Steps to create files in Magento 2 are given below.

    STEP 1 : Content of File

    $url = "https://webkul.com/wp-content/themes/webkul/inc/E-Commerce-Marketplace-Use-Case.pdf";
    $pdfContent = file_get_contents($url);
    
    • file_get_contents(_path) : In php this is best and preferred way to read complete file into string
      • Parameters:
        • _pathFile path which need to read.
        • offset : Specify position from where file reading starts.
        • maxlen : Define length of data which need to read. By default it read complete data. 

    STEP 2 : Check directory and Create Directory

    $filePath = "/webkul/attachment/file/pdf/";
    $pdfPath = $this->_directoryList->getPath('media').$filePath;
    if (!is_dir($pdfPath)) {
    $ioAdapter = $this->_file;
    $ioAdapter->mkdir($pdfPath, 0775);
    }
    • _directoryList : Is an object of “Magento\Framework\App\Filesystem\DirectoryList” class.
    • getPath(directory_type) : It returns path of desired directory type.
    • is_dir(directory_path) : Check for directory and return True if directory exist.
    • _file : Is an object of “Magento\Framework\Filesystem\Io\File” class.
    • mkdir(directory_path,  directory_permission) : Create directory of given path,
      • Parameters:
        • directory_path : Path of directory (“/webkul/attachment/file/pdf“)
        • directory_permission : File permission as per as requirement (0644).

    step 3 : Create File Using File Content

    $fileName = "webkul.pdf";
    $ioAdapter->open(array('path'=>$pdfPath));
    $ioAdapter->write($fileName, $pdfContent, 0666);
    • open : Helps to open given path where file need to create.
    • write(_fileName, _fileContent, _filePermission) :  Create file inside given path.
      • Parameters :
        • _filename : Specify file name
        • _filecontent : Content of file which need to create
        • _filePermission : Permission of file which need to assign as per as requirement.

     

    Searching for an experienced
    Magento Company ?
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    1 comments

  • Andzej Telican
    How to set file encoding with this method ?
  • Back to Top

    Table of Content