Search code examples
typo3extbasetypo3-extensions

How to open a file in TYPO3 extbase extension controller?


I need to read an file inside of the extension controller, here as example my extension key is myext_key and the file I want to open is a JSON file data.json in the Resources/Private/JSON directory. My research gave me, that the best way to open a file wouldn't be with file_get_contents($path), instead with \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($path).

So I tried it with the following code, but that didn't work:

$content = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL('EXT:myext_key/Resources/Private/JSON/data.json');

Thanks for all help!


Solution

  • Not sure if anything is wrong with file_get_contents(), other than memory implications, because file_get_contents() essentially assigns a variable with the whole file content. As long as you are dealing with a small .json file is small you should be in the safe.

    The method to get the absolute file name of a file inside an extension directory is getFileAbsFileName()

    $fileContent = file_get_contents(
        \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:myext_key/Resources/Private/JSON/data.json')
    );