Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    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

    • 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

    • _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

    • 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.


    . . .

    Comment (1)

    Add Your Comment

  • Andzej Telican
    How to set file encoding with this method ?
  • Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again

    Table of Content

    Hide Index