symfony文件导入(csv)

时间:2013-05-01 14:48:26

标签: php symfony

我想从csv文件将数据导入数据库,但我不能这样做。我的代码如下。我想从csv打印数据,但它给了我错误:

Warning: fopen(soubor.csv): failed to open stream: No such file or directory in /var/www/VWM/src/VWM/ProjektBundle/Controller/DefaultController.php line 56

我该如何解决?

public function addProductAction() {
    $product = new Product;
    $form = $this->createForm(new ProductType(), $product);
    $form2 = $this->get('form.factory')->createNamedBuilder('form2name')
        ->add('submitFile', 'file', array('label' => 'CSV'))
        ->getForm();

    $m = 'nevyplněno';
    $request = $this->getRequest();
    if('POST' === $request->getMethod()) {

        // add one product, it works
        if($request->request->has('vwm_projektbundle_producttype')) {
            $form->bindRequest($request);
            if($form->isValid()) {
                return $this->forward('VWMProjektBundle:Default:result', array('product' => $product));
            } else {
                $m = 'Chybně vyplněný formulář';
            }
        }

        // add products from CSV
        if($request->request->has('form2name')) {
            $form2->bindRequest($request);
            if($form2->isValid()) {
                // Get File
                $file = $form2->get('submitFile');
                // your csv file here when you hit submit button
                $filename = $file->getData();           
                //print_r($data); // this returns filename.csv
                $row = 1;
                if (($handle = fopen($filename, "r")) !== FALSE) {
                    while (($data = fgetcsv($handle, 100, ";")) !== FALSE) {
                        $num = count($data);
                        echo "<p> $num fields in line $row: <br /></p>\n";
                        $row++;
                        for ($c=0; $c < $num; $c++) {
                            echo $data[$c] . "<br />\n";
                      }
                    }
                    fclose($handle);
                }
            }
        }
    }

    return array(
        'form' => $form->createView(),
        'form2' => $form2->createView(),
        'm' => $m,
        );
}

2 个答案:

答案 0 :(得分:0)

替换这些行:

$filename = $file->getData();           
//print_r($data); // this returns filename.csv

使用:

$filename = $file->getData();           
print_r($data); // this returns filename.csv
die(' <-- actual path');

您在文件中看到的路径是否正确?

要测试代码,您可以先将绝对路径放在 $ filename var中。如果它无法使用正确的绝对路径,请检查文件的权限。

答案 1 :(得分:0)

尝试使用:

$csvFile = $form->get('csvFile')->getData()->getPathName();

它将返回您的完整临时文件路径名。