datether datether - 8 months ago 41
PHP Question

PHP Processing stream_get_contents into an array

I am having troubles converting a string which contains tab delimited CSV output
into an array. While using the following code :

$data = stream_get_contents($request->getShipmentReport());

I get back data as following:

Date Shipped Comments Feedback Arrived on Time
5/11/15 2 comment response Yes

Now I would like to process this data into an array with the returned headers(line 1) as the index containing the value for each line which follows after that.

I am trying to end up with something like this :

$line['Date'] = 5/11/15
$line['Shipped'] = 2
$line['Feedback'] = response
$line['Arrived on Time'] yes

What would be the best way to achieve this ?


I recommend using a library for handling CSV for example the CSV-Package by The League of Extraordinary Packages

You can pass your data and start working with array structures right away:

$csvString = stream_get_contents($request->getShipmentReport());
$csvReader = \League\Csv\Reader::createFromString($csvString);
$data = $csvReader->fetchAssoc(
    array('Date', 'Shipped', 'Comments', 'Feedback', 'Arrived on Time')
// Or since line 0 contains header
$data = $csvReader->fetchAssoc(0); // 0 is offset of dataset containing keys

Now your data should be in a structure like:

$data = array(
        'Date' => '5/11/15',
        'Shipped' => '2',

You can even filter out specific datasets and all kinds of fancy stuff. Just check the documentation I linked to.