1

I want to open CSV (comma separated value) file in PHP by column, i want to take all datas from 3 columns. I tried with this code, but this only shows me data by row:

  $row = 1;
    if (($handle = fopen("ut.csv", "r")) !== FALSE) {
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
      }
      fclose($handle);
    }

How i can take all datas from one column ?

EXAMPLE: This i my file in Excel, which is exported to SCV: http://prntscr.com/mzcfcw

I want to take in php values from colum Name and Price and find duplicate values in column Name, compare their prices.

11
  • Can you show a sample input (a few rows) and the output you want from that? Commented Mar 18, 2019 at 7:44
  • @NigelRen I added Commented Mar 18, 2019 at 7:47
  • You should have a look at array_count_values : php.net/manual/en/function.array-count-values.php Commented Mar 18, 2019 at 7:49
  • @kuh-chan problem is how i can take values from excel by column Commented Mar 18, 2019 at 7:51
  • It's not an excel file. It's a CSV (comma separated value) file. Commented Mar 18, 2019 at 7:52

1 Answer 1

2

fgetcsv parses the given handle line by line (rows). It isn't possible to parse a csv file by column using core php. However, if you know the position of the 3 columns for which you wish to access the values, you could simply ignore all other columns:

 //position (zero indexed) of required columns
 $columnsToProcess=[0,3,4]
 for ($c=0; $c < $num; $c++) {
 //do something with value if column's index is in the required columns array 
            if(in_array($c,$columnsToProcess)){
                //value at position $c equals $data[$c]
                echo $data[$c] . "<br />\n";
             }          
        }

Moe info about fgetcsv : http://php.net/manual/en/function.fgetcsv.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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