0

My PHP app will upload a selected csv file into memory. It is then converted into an array using str_getcsv as shown below.

//get file from session variable created in upload.php
$uploadedfile = str_getcsv($_SESSION['uploadedfile'], "\n");

//remove first two rows as these contain headers
unset($uploadedfile[0]);
unset($uploadedfile[1]);

the array currently looks like this:

array(4174) {
  [2]=>
string(180) "productID,ProductBarcode,brand,productType,productName"
  [3]=>
string(178) "productID,ProductBarcode,brand,productType,productName"

I need to loop through each row and explode the comma separated value into a multidimensional array. So it looks something like this:

array() {
 [row2]=>
   "productID => 001"
   "ProductBarcode=>101010"
   "brand=>apple"
   "productType=>notebook"
   "productName=>Macbook pro"
 [row3]=>
   "productID => 002"
   "ProductBarcode=>20202"
   "brand=>apple"
   "productType=>desktop"
   "productName=>iMac"
 }

I believe this question was tring to answer a similar thing but the answer wasn't provided: PHP: Parsing Comma-Separated Values Between Square Brackets into Multi-Dimensional Array

2
  • 1
    str_getcsv takes a single line of text and decomposes it into an array. it does not work on an entire file. to take an entire csv file, you'd have to loop on each line and str_getcsv that line individually. Commented Nov 5, 2013 at 15:49
  • What Marc said. Also maybe look at fgetcsv Commented Nov 5, 2013 at 15:51

1 Answer 1

1

Try using file to read the file lines into an array. Then get the first row to use as headers with array_shift. After that just loop and read the line into an array with str_getcsv and combine with the headers:

$uploadedfile = file($_SESSION['uploadedfile'], FILE_IGNORE_NEW_LINES);
$headers = array_shift($uploadedfile);
unset($uploadedfile[0]);

foreach($uploadedfile as $line) {
    $data[] = array_combine($headers, str_getcsv($line));
}
Sign up to request clarification or add additional context in comments.

1 Comment

@mickmackusa: That was 5 years ago but OK.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.