Chris99391
Chris99391

Reputation: 581

Limitation of reading a CSV file

I have a CSV file with several lines and I would like in php only recover the data whose column 1 the value is equal to 27, how can I do that?

That's what I already did:

<?php

require(dirname(__FILE__) . '/config/config.inc.php');

$fileDir = 'stock.csv';

$fileCsv = file_get_contents($fileDir);

echo $fileCsv;

My CSV file has 3 columns:

| number | ref | stock |
|   19   | 135 |   10  |
|   27   | 656 |   20  |

Thank you.

Upvotes: 0

Views: 652

Answers (2)

IsThisJavascript
IsThisJavascript

Reputation: 1716

As RiggsFolly pointed out; fgetscsv() is your best tool for this.

$fileDir = 'stock.csv';
//open the file for reading
$fileCsv = fopen($fileDir,"r");
//initialize our output array
$outputData = array();
//define the line length required for fgetcsv
$lineLength = 100;
//loop the contents of csv and split by `,`
while($row = fgetcsv($fileCsv,$lineLength,',')){
   //does our first column equal 27?
    if($row[0] == 27){
        //store the full row into our output array
        $outputData[] = $row;
    }
}
//output
print_r($outputData);

Upvotes: 2

Lucarnosky
Lucarnosky

Reputation: 514

If you use a file in a directory you can use this piece of code

$csv = array_map('str_getcsv', file('stock.csv'));

It will return an associative array where you can handle with a foreach like this

$just27Array = array();
foreach($csv as $index => $valueArray){
    if($valueArray['number'] == 27)
       $just27Array[] = $valueArray;
}

In your $just27Array variable you'll have a series of array where number is equal to 27

Upvotes: 1

Related Questions