I am trying to import a .csv file in Symfony 2. I've created a file form and now I want to persist it in my database.
Here is my handler file where I want to make the .csv treatment and persist it:
public function process()
{
if ($this->request->getMethod() == 'POST')
{
$this->form->bindRequest($this->request);
$tableau = array();
$i = 0;
$c = 0;
$num = 0;
if (isset($_FILES['file']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,'r');
$row = 1;
$handle = fopen("$file", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num =+ count($data);
$row++;
for ($c = $i; $c < $num; $c++)
{
$tableau[$c] = $data[$c];
$i++;
}
}
}
$tableau[$c+1] = $i;
/*
if ($this->form->isValid())
{
print_r($this->form->getData());
$this->onSuccess($this->form->getData());
return true;
}
*/
}
return false;
}
When I'm trying to test it some text appears on top of my page:
Array ( [fichier] => Symfony\Component\HttpFoundation\File\UploadedFile Object ( [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => testcsv.csv [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => text/csv [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 491 [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [pathName:SplFileInfo:private] => /Applications/MAMP/tmp/php/phpSr5O5S [fileName:SplFileInfo:private] => phpSr5O5S ) )
I don't understand those things.
If you want to do a proper symfony2 way you should create a symfony form to submit the file. For example:
// Your Controller.php
$form = $this->createFormBuilder()
->add('submitFile', 'file', array('label' => 'File to Submit'))
->getForm();
// Check if we are posting stuff
if ($request->getMethod('post') == 'POST') {
// Bind request to the form
$form->bindRequest($request);
// If form is valid
if ($form->isValid()) {
// Get file
$file = $form->get('submitFile');
// Your csv file here when you hit submit button
$file->getData();
}
}
return $this->render('YourBundle:YourControllerName:index.html.twig',
array('form' => $form->createView(),)
);
Twig:
<!-- index.html.twig Twig part -->
{% extends "YourBundle::layout.html.twig" %}
{% block content %}
<form action="" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
{% endblock %}
Dont forget that {{ form_enctype(form) }}
is important to tell that we are sending file. Symfony2 will generate enctype="multipart/form-data"
tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With