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?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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?
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
If you would like to try another way, maybe use Magento\Framework\Filesystem\Io\File and Magento\Framework\Convert\ConvertArray. ConvertArray is useful to make an xml file from a multidimensional array and File can write it for you (and check permissions, create directories and more). Here is a basic example:
public function __construct(
\Magento\Framework\Filesystem\Io\File $file,
\Magento\Framework\Convert\ConvertArray $convertArray
)
{
$this->file = $file;
$this->convertArray = $convertArray;
}
public function createMyXmlFile($assocArray, $rootNodeName, $filename = 'file.xml')
{
// ConvertArray function assocToXml to create SimpleXMLElement
$simpleXmlContents = $this->convertArray->assocToXml($assocArray,rootNodeName);
// convert it to xml using asXML() function
$content = $simpleXmlContents->asXML();
$this->file->write($filename, $contents);
}
if my array is :
$myArray = array(
'fruit' => 'apple',
'vegetables' => array('vegetable_1' => 'carrot', 'vegetable_2' => 'tomato'),
'meat' => 'none',
'sweets' => 'chocolate');
and I call my function:
$simpleXmlContents = $this->convertArray->assocToXml($myArray, 'diner');
$this->file->write($myXmlFile,$simpleXmlContents->asXML());
I would get the following in myfile.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<diner><fruit>apple</fruit><vegetables><vegetable_1>carrot</vegetable_1>
<vegetable_2>tomato</vegetable_2></vegetables><meat>none</meat>
<sweets>chocolate</sweets></diner>