1

I need to create a json file with data and store that file in specific directory of magento 2. Can any one please tell me how we can achieve this in magento2 in standard way like file system.

Please don't suggest PHP way as this might not be the standard way due to which magento will restrict module from uploading.

any help will be appreciated. thanks in advance

0

I don't know if this is a correct way of implementing but i find this in core file of magento \vendor\magento\framework\Code\GeneratedFiles.php

Please suggest on this.

use Magento\Framework\Filesystem\Directory\WriteFactory;

/**
 * @var WriteInterface
 */
prtected $write;

public function __construct(
    ...
    WriteFactory $writeFactory,
    ....
) {
    ....
    $this->write = $writeFactory->create(BP);
    ....
}

And for file creation below code in method.

$this->write->writeFile($relativePath, $content);

If it is correct then hope this will help someone.

0
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;


protected $filesystem;

protected $jsonDir;

public function __construct(
    ...
    Filesystem $filesystem,
    ....
) {
    ....
    $this->filesystem = $filesystem;
    $this->jsonDir=$filesystem->getDirectoryWrite(DirectoryList::MEDIA);
    ....
}

So now prepare your JSON content and write to directory,

$this->jsonDir->writeFile($relativePath, $content);

Where $relativePath is relative path of of file and $content is your JSON content.

  • Sorry but it gives Unknown directory type: 'myFiles' – Ashish Madankar M2 Professiona Sep 26 '17 at 12:18
  • Updated the answer :) @AshishMadankar – Keyur Shah Sep 26 '17 at 12:41
  • Thanks for this update but what if i want to create my own directory on root and what do you think about the code which i posted in answer – Ashish Madankar M2 Professiona Sep 27 '17 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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