Home > database >  Data Import (TXT to CSV in Laravel Application)
Data Import (TXT to CSV in Laravel Application)

Time:11-15

I was wondering if anyone could provide me with any pointers with regards to Data Importing within Laravel. I am building a small CRM system for my business in which I have exported a data backup from my old CRM system in the form of a (TXT file - This was the only option I had)

Within the new system I have built, I have managed to implement a simple Data Import feature which allows the import of CSV file data.

I have converted the TXT file in to a CSV file. Although, from here, I'm a little unsure of how to actually get my data to match up to the columns I have within the datatables within my application. I'm guessing the headings within the converted TXT file should match up to the headings I have specified within my datatables, although, is there any other requirements outside of this in terms of the formatting of the data from TXT to CSV?

Any small pointers would be most appreciated! :-)

Example:

Rough Example of how my data is formatted within the TXT file (I had to remove my client data, I've removed the values from most of the headings, but hopefully this provides an insight in to the structure of the file I am wanting to reimport in the form of a CSV

iprospects|psurname|pforename|pcmiddle|paddress1|paddress2|ptown|ppostcode|pdob|ptelephone|pwife|pterms|pdate|leadtype|pindustry|pbusinessname|pleadvalue|pnotes|pusers|paddons|cp
001|JOE BLOGGS||123 TEST ROAD||CITYGOESHERE 

Thanks.

CodePudding user response:

CSV is very simple format. So we have delimiter of rows and delimiter of columns. So we need only to split our data on array pieces:

$rowDelimiter = "\n"; // is a new line
$colDelimiter = ",";
$raw = ""; // here you place your CSV content (file_get_contents('somefile.csv') for example)
$data = []; // result data array
foreach (explode($rowDelimiter, $raw) as $rowIndex => $row) {
  $data[$rowIndex] = [];
  foreach (explode($colDelimiter, $row) as $colIndex => $col) {
    $data[$rowIndex][$colIndex] = $col;
  }
}

So in result we have $data array, where every entrie is a row, and every row entrie is a col. And with this we can make models.

CodePudding user response:

From the looks of your data it looks like you can use something like below:

$textFileHandle = fopen('input.txt', 'r');
$csvFileHandle = fopen('output.csv', 'w');
do {
   $line = fgetcsv($textFileHandle, 0, '|');
   fputcsv($csvFileHandle, $line);
} while($line !== false);

This utilises the fact that your text file looks like a CSV file that is pipe delimited (PSV?) and converts it into a true CSV file.

  • Related