创建新的xml文件并使用symfony2.8保存在系统中

时间:2016-10-21 11:23:30

标签: php xml symfony xml-parsing save

我想创建 .xml 文件并使用 symfony2.8 直接从控制器保存, xml 文件应该自动附加一次创造了一天。

帮助将不胜感激

$mainNode = new \SimpleXMLElement("<?xml version='1.0' encoding='UTF-8'?><items></items>"); 
$productNode = $mainNode->addChild('product');
$productNode->addChild( 'productCode', '1235846' );
$mainNode->asXML();

2 个答案:

答案 0 :(得分:1)

您可以这样做:

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);
}

答案 1 :(得分:0)

            $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);
            }