How to read file to string from pub/media directory?

To get the directory, use Magento\App\Filesystem\DirectoryList:

$om = \Magento\Core\Model\ObjectManager::getInstance();
$directoryList = $om->get(\Magento\App\Filesystem\DirectoryList::class);

$pubMediaDir = $directoryList->getPath(\Magento\App\Filesystem\DirectoryList::MEDIA);

In a custom class you will not instantiate the object manager, but instead inject Magento\App\Filesystem\DirectoryList via di.xml, then use it like this:

$pubMediaDir = $this->directoryList->getPath(DirectoryList::MEDIA);

To read the file to a string, use the PHP function \file_get_contents()

Tags:

Magento2