Jump to content

PHP: Returning and naming specific fields from a CSV in an array


Go to solution Solved by Barand,

Recommended Posts

I'm currently writing a script to display the fields from a large CSV and display them in arrays. Currently I have a working script as below:

 

<?php
function csvToArray($csvFile){
    $file_to_read = fopen($csvFile, 'r');
    while (!feof($file_to_read) ) {
        $lines[] = fgetcsv($file_to_read, 1000, ',');
    }
    fclose($file_to_read);
    return $lines;
}

$csvFile = 'example.csv';
$csv = csvToArray($csvFile);

echo '<pre>';
print_r($csv);
echo '</pre>';
?>


This returns every line of the CSV into arrays.

However, what I want to do next is have only specific fields be returned in these arrays, and have said fields be named. So, for example, right now the output looks something like:

(0) =>
(1) => £100
(2)=> Cancelled
(3) =>
(4) =>

But what I want to output would be something like:

(Subscription Cost) => £100
(Subscription Status) => Cancelled

Can someone give me a hand with how to achieve this? I've never used any CSV functions with PHP before so I'm starting from scratch currently with my knowledge.

  • Solution

No idea what your csv data looks like, so going to use this (mytest.csv)...

,100,"Cancelled",,
,200,"Active",,
,300,"Pending",,

then

$fp = fopen('files/mytest.csv', 'r');
while ($row = fgetcsv($fp)) {
    $data[] = [ 'cost' => $row[1],
                'status' => $row[2]
              ];
}
fclose($fp);

echo '<pre>' . print_r($data, 1) . '</pre>';

giving

Array
(
    [0] => Array
        (
            [cost] => 100
            [status] => Cancelled
        )

    [1] => Array
        (
            [cost] => 200
            [status] => Active
        )

    [2] => Array
        (
            [cost] => 300
            [status] => Pending
        )

)

 

Quote

echo '<pre>';

print_r($csv);

echo '</pre>';

Instead of doing your final output as above where you simply dump the entire contents that you read in, why not simply print only the array elements that you want?  As barand showed you your read process could only save specific elements of the csv lines you are reading.  You could simply do the output right there instead of saving an array and then processing the data a second time.

More - 

If you know how your csv file is laid out you could do this also:

$filename = 'example.csv';
if ($hdl = fopen($filename, 'r'))
	while(list($a,$b,$c,$d, $e) = fgetcsv($hdl,1000))
		echo "$a $d $e<br>";	//  simple output of a single line
else
	echo "Could not open file: $filename";
exit();

Note - I only use lowercase names.  Makes it less prone to typos down the road.

2nd note - the echo line shows how to only print certain fields from your csv lines.  And it does a very simple output.  Instead you could begin an html table prior to beginning the while and then insert table rows for each line your read.  Then close the table after the while ends.

The key to all this is knowing your csv layout and providing fieldnames for each item in a row and then only referencing the ones you want to use.  The list() construct works very nicely for this kind of thing.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.