Searching a CSV With PHP

佐手、 提交于 2019-12-11 06:28:43

问题


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.


回答1:


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) */

}



回答2:


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:

<?
$file=file('yourfilepath');
$list=array();
foreach($file as $value){
    if(stristr($value,'Intel Pentium Dual')){create your $cpuscore here}
}
print_r($result);
?>


来源:https://stackoverflow.com/questions/12922772/searching-a-csv-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!