user1751197
user1751197

Reputation: 31

Searching a CSV With PHP

I have a large CSV file. The first column contains the name of a processor. The second, the processor's benchmark score. EG:

Intel Pentium Dual T3400 @ 2.16GHz,1322

Using a PHP script, I would like to search the first column for a string (EG. Pentium Dual T3400), and (assuming that there is only one result per search, else return an error message) create a variable containing the value of the second column.

I don't know if this will help, but I was sort of hoping it would look a little like this:

$cpuscore = csvsearch(CSV_file,query_string,column#_to_search,column#_to_return)

Where $cpuscore would contain the score of the processor name that matches the search query.

Feel free to suggest something that would produce similar results. I have MySQL, but I don't have the permissions to import tables from CSV.

Upvotes: 1

Views: 7655

Answers (2)

Scott Hillson
Scott Hillson

Reputation: 853

I like to iterate through each line of a csv file and find the words i'm looking for, and compile a result from there. Here's something to get you started:

     <?php
   $query = "Intel Core i7 3600M"     
   $file = file('db.csv');    
       foreach($file as $value) { 
         if(stristr($value,$query)){
            $items = explode(",", $value); echo $items[1];
              }; 
         };
    ?>

Upvotes: 0

Ray
Ray

Reputation: 793

You can use the php function fgetcsv(), http://php.net/manual/en/function.fgetcsv.php to traverse the csv file row by row. For instance:

$ch = fopen($path_to_file, "r");
$found = '';

/* If your csv file's first row contains Column Description you can use this to remove the first row in the while */
$header_row = fgetcsv($ch);

/* This will loop through all the rows until it reaches the end */
while(($row = fgetcsv($ch)) !== FALSE) {

    /* $row is an array of columns from that row starting at 0 */
    $first_column = $row[0];

    /* Here you can do your search */
    /* If found $found = $row[1]; */
    /* Now $found will contain the 2nd column value (if found) */

}

Upvotes: 1

Related Questions