Jump to content

Searching Through A Csv And Only Returning Certain Rows And Certain Columns


blight

Recommended Posts

Hi Everyone

 

Struggling with something that should be incredibly simple

 

I need to search through a csv file for a certain string and then return the rows which contain that string and only certain columns for that row

So I have the simple part to display only the relevant columns but I cant find any info on how to search and only return the relevant rows? Your assistance would be highly appreciated.

 

<?php

 

if (($handle = fopen("filename.csv", "r")) !== FALSE) {

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

echo "$data[1] $data[2] $data[3] $data[18] $data[34] <br />\n";

}

fclose($handle);

}

 

?>

Firstly,

Your while loop will loop through the entire csv file. You can write an if statement to capture (or echo) the data you need. So, a small alteration could be...

 

 


if (($handle = fopen("filename.csv", "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   if ($data[1] === <whateverIAmLookingFor>) {
     echo $data[2] . "\n";    // Or do whatever you need to do with that data.
   }
 }
 fclose($handle);
}

 

You could also grab the array in the while loop and work with it later (personally... I prefer this):

 

 

if (($handle = fopen("filename.csv", "r")) !== FALSE) {
 $row=0;
 $csv_row = array();
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   if ($data[1] === <whateverIAmLookingFor>) {
     $csv_row = $data;
   }
 }
 fclose($handle);

 // Do whatever you need to with $csv_array...
 echo $csv_row[2] . "\n";
}

 

If you're having problems reading in the CSV file (perhaps only returning one row), it could be funny line endings. Try setting:

 

ini_set('auto_detect_line_endings', true);

Hi Barand

 

Thanks - but I cant figure out the syntax to combine the if statement and the fgetcsv function...

 

As you don't tell us what you are searching for and in which column(s), neither can I.

Here's something I just used to do something similar. Mine looked for empty columns and replaced "" with NULL to prep for DB entry, but you should be able to get this to look for your values and respond appropriately:

 

$file_handle = fopen("requirementsTable.csv", "r");
if($file_handle){echo "
We opened requiremntsTable.csv!
";}
while (!feof($file_handle) )
{
$cellBlock = fgetcsv($file_handle, 1024);
for($i=0; $i < count($cellBlock); $i++)
{
if($cellBlock[$i] == ""|| is_null($cellBlock[$i])){$cellBlock[$i]="NULL";}
if($cellBlock[$i] != "NULL") {
$cellBlock[$i] = addslashes($cellBlock[$i]);
$cellBlock[$i] = "'".$cellBlock[$i]."'";
}
// echo "
I counter is: ".$i;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.