alistaircol
alistaircol

Reputation: 1453

PHP CSV from S3 as string - want to convert to array

I have some code which downloads a CSV file from an S3 bucket into a PHP variable.

I want to get this CSV content (a string) from this variable and convert it into an array.

I'm having some issues reading from my php://memory resource.

When I print the $csv_fread or $rows I see nothing.

Dumping the $csv_fstat shows the correct length of my file I uploaded and then downloaded and put into the $file_contents string and wrote to the $csv resource.

Any help appreciated.

  // use Aws\S3\S3Client;
  $result = $this->client->getObject([
    'Bucket' => $this->bucket,
    'Key'  => $id
  ]);

  $file_contents = $result['Body'];

  $csv = fopen('php://memory', 'r+');
  if ($csv === false) {
    throw new Exception('Could not create file wrapper');
  }
  if (fwrite($csv, $file_contents) === false) {
    throw new Exception('Could not write contents to file wrapper');
  }

  $csv_fstat = fstat($csv);
  $csv_fread = fread($csv, $csv_fstat['size']);

  if ($csv_fread === false) {
    throw new Exception('there was an error reading shit');
  }

  $header = null;
  $rows = [];
  while (($row = fgetcsv($csv, 0, ',')) !== false) {
    if (!$header) {
      $header = [];
      foreach ($row as $v) {
        $header_raw[] = $v;
        $hcounts = array_count_values($header_raw);
        $header[] = $hcounts[$v] > 1 ? $v . $hcounts[$v] : $v;
      }
    } else {
      foreach ($row as &$l) {
        $l = trim($l);
      }
      $rows[] = array_combine($header, $row);
    }
  }
  fclose($csv);

Upvotes: 2

Views: 1857

Answers (1)

alistaircol
alistaircol

Reputation: 1453

I figured out the issue. Needed to do:

rewind($csv);

After fwrite

Upvotes: 2

Related Questions