如何解决如何在 Symfony/PHP 中处理错误的 CSV 文件导入
我正在从 csv 上传大量数据而没有问题,但我想保护可能的用户错误,因为他们有可能将格式错误的 csv ...
问题是每次启动表单时我都会截断我的表格...
ImportController.php
$form = $this->createFormBuilder()
->add('form',FileType::class,[
'attr' => ['accept' => '.csv','class' => 'custom-file-input'],'label' => 'Import'
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
/**
* @var UploadedFile
*/
$file = $form->get('form')->getData();
$connection = $em->getConnection();
$platform = $connection->getDatabasePlatform();
$connection->beginTransaction();
$connection->executeQuery($platform->getTruncateTableSQL('MyTable',true));
$this->getDoctrine()->getManager()->getRepository(MyTable::class)->importMyData($file);
$this->addFlash('success',"The csv has been successfully imported");
return $this->redirectToRoute('import');
}
MyTableRepository.php
public function importMyData($file)
{
$em = $this->entityManager;
if (($handle = fopen($file->getPathname(),"r")) !== false)
{
$count = 0;
$batchSize = 1000;
$data = fgetcsv($handle,",");
while (($data = fgetcsv($handle,")) !== false)
{
$count++;
$entity = new MyTable();
// 40 entity fields...
$entity->setFieldOne($data[0]);
$entity->setFieldTwo($data[1]);
//....
$entity->setFieldForty($data[39]);
$em->persist($entity);
if (($count % $batchSize) === 0 )
{
$em->flush();
$em->clear();
}
}
fclose($handle);
$em->flush();
$em->clear();
}
}
我只是希望当一个错误的 CSV 文件被启动时表不会被截断
解决方法
您可以在插入数据库之前清理和验证数据。您可以尝试多种方式。首先,我会使用 Symfony 文件验证器来确保检查已上传的有效文件。
要验证每一行,您可以使用自定义回调验证器或数组的原始值 Validate Raw Data
//call the validator in the repository
$validator = Validation::createValidator();
// sample input
$input = [
'field_1' => 'hello','field_2' => 'test@email.tld','field_40' => 3
];
//define the constraints for each row
$constraint = new Assert\Collection([
// the keys correspond to the keys in the input array
'field_1' => new Assert\Collection([
'first_name' => new Assert\Length(['min' => 101]),'last_name' => new Assert\Length(['min' => 1]),]),'field_2' => new Assert\Email(),'field_40' => new Assert\Length(['min' => 102])
]);
while (($data = fgetcsv($handle,",")) !== false) {
$violations = $validator->validate($data,$constraint);
// you can skip the row or log the error
if ($violations->count() > 0) {
continue;
}
}
,
感谢你们所有人,我很愚蠢,我只是放了一个“try catch”,如果 importMyData 函数发生错误,它会返回其他东西,然后我检查我的控制器,如果这返回值......如果是这样,我重定向等
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。