Magento 2 – Generate XML File Programmatically

filemagento2xml

I need to generate an .xml file from my extension. Inside Namespace/Module/view/adminhtml/ui_component/ folder,

I need to do this pro-grammatically because the .xml file will be generated based on data collection, is there a way to do this?

Best Answer

For now i'm using php original function to write/create file inside my extension directory like this:

    public function __construct(
      \Magento\Framework\Module\Dir\Reader $moduleReader
      )
    {
        $this->customAttribute = $customAttribute;
        $baseDir = $moduleReader->getModuleDir('', 'Namespace_Module');
        $this->dir = $baseDir . '/view/adminhtml/ui_component';
    }

    public function writeFile() {
        $dir = $this->dir;
        $fileName = 'test.xml';
        $content =  '<test>Test</test>';

        $myfile = fopen($dir . '/' . $fileName, "w") or die("Unable to open file!");
        try {
          fwrite($myfile, $content);
          fclose($myfile);
        } catch (Exception $e) {
          $this->_logger($e->getMessage());
        }
        return;
     }

if there's more proper way to do it in Magento 2 please let me know, and i will accept the answer for this question, but for now if anyone want to use this as a solution it's working properly for me but i do not recommend it

Related Topic