Reputation: 310
I want to create .xml file and save into directly from controller using symfony2.8, xml file should be auto append once it created for a day.
Help will be appreciate
$mainNode = new \SimpleXMLElement("<?xml version='1.0' encoding='UTF-8'?><items></items>");
$productNode = $mainNode->addChild('product');
$productNode->addChild( 'productCode', '1235846' );
$mainNode->asXML();
Upvotes: 0
Views: 3988
Reputation: 310
$filePath = __DIR__ . '/../../../app/logs/xml/';
$fileName = 'xmlLog_' . date('d.m.Y') . '.xml';
if (file_exists($filePath . $fileName)) {
// append data if file already exist
$xml = simplexml_load_file($filePath . $fileName);
$productList = $xml->productList;
$lastElement = count($productList->product);
foreach ($logArray as $key => $data) {
$rN = $productList->addChild('product');
$rN->addChild('id', $lastElement);
$rN->addChild('productId', $logArray[$key]['productId']);
$rN->addChild('type', $logArray[$key]['type']);
$rN->addChild('oldValue', $logArray[$key]['oldValue']);
$rN->addChild('adjustment', $logArray[$key]['adjustment']);
$rN->addChild('newValue', $logArray[$key]['newValue']);
$lastElement++;
}
$xml->asXML($filePath . $fileName);
} else {
// create new file if not exist
$mainNode = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><inventory></inventory>');
$productNode = $mainNode->addChild('productList');
foreach ($logArray as $key => $data) {
$rN = $productNode->addChild('product');
$rN->addChild('id', $key + 1);
$rN->addChild('productId', $logArray[$key]['productId']);
$rN->addChild('type', $logArray[$key]['type']);
$rN->addChild('oldValue', $logArray[$key]['oldValue']);
$rN->addChild('adjustment', $logArray[$key]['adjustment']);
$rN->addChild('newValue', $logArray[$key]['newValue']);
}
$fs = new Filesystem();
$fs->mkdir($filePath);
$mainNode->asXML($filePath . $fileName);
}
Upvotes: 0
Reputation: 9362
You can do something like this:
public function updateTodaysXMLAction()
{
$todaysFile = '/path/to/file/' . date('d-m-Y').'.xml';
$xmlFileContents = file_get_contents($todaysFile);
$xml = new \SimpleXMLElement($xmlFileContents);
//make updates as needed
$xml->addChild('product')->addChild( 'productCode', '1235846' );
// Save out the file
$xml->asXML($todaysFile);
}
Upvotes: 2