How to write files programmatically in Magento 2
To write files programmatically in Magento 2, use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/** * @param string $directory * @param string $relativeFileName * @param string $contents * @return void */ function df_file_write($directory, $relativeFileName, $contents) { /** @var \Magento\Framework\App\ObjectManager $om */ $om = \Magento\Framework\App\ObjectManager::getInstance(); /** @var \Magento\Framework\Filesystem $filesystem */ $filesystem = $om->get('Magento\Framework\Filesystem'); /** @var \Magento\Framework\Filesystem\Directory\WriteInterface|\Magento\Framework\Filesystem\Directory\Write $writer */ $writer = $filesystem->getDirectoryWrite($directory); /** @var \Magento\Framework\Filesystem\File\WriteInterface|\Magento\Framework\Filesystem\File\Write $file */ $file = $writer->openFile($relativeFileName, 'w'); try { $file->lock(); try { $file->write($contents); } finally { $file->unlock(); } } finally { $file->close(); } } |