Hi I am trying to get the csv file data and display that data in my view .
Below is my controller function :
public function indexAction()
{
$delimiter = ',';
$enclosure = '""';
$escape = '//';
$filename = 'data' . DIRECTORY_SEPARATOR . 'csv' . DIRECTORY_SEPARATOR . 'StoreDepartment.csv';;
$this->file = new SplFileObject($filename);
$this->file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
$this->file->setCsvControl($delimiter, $enclosure, $escape);
$this->useFirstRecordAsHeader = true;
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'text/csv');
$contents = $this->file->fread($this->file->getSize());
$response->setContent($contents);
$views = new ViewModel(array('text'=>$response));
return $views;
}
I am getting all the data as csv. but i am getting below warning :
Warning: SplFileObject::setCsvControl(): escape must be a character
Also i want to convert this data into JSON or Array format is it possible ?
Main concept is i want to store this data into my database table. So what format is suitable to store data in database ? Please Help
How to resolve both the errors ?
The warning is because your $escape variable is two characters not one.
$escape = '/';
or
$escape = "//";
Since you only need to escape backslashes when using double quotes.
As for your question regarding how to store in database. It's very hard to say without knowing what you need to do and what data is in the CSV. However I would suggest having a one to one mapping between a CSV column and a database column. Though the number of tables you need would really depend on the data and use cases. There are also a few situations when you may want to just store the raw data but again more information would be required and it would still be an opinionated answer that would be given