2

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

3 Answers 3

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.

3
  • Sorry but it gives Unknown directory type: 'myFiles' Commented Sep 26, 2017 at 12:18
  • Updated the answer :) @AshishMadankar Commented Sep 26, 2017 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 Commented Sep 27, 2017 at 6:27
0

As @Keyur Shah wrote, just add third parameter $mode = 'w' like this

$this->jsonDir->writeFile($relativePath, $content, $mode = 'w');

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.