2012-10-16 121 views
1

我有一個很大的CSV文件。第一列包含處理器的名稱。第二,處理器的基準分數。 EG:使用PHP搜索CSV

Intel奔騰雙T3400 @ 2.16GHz的,1322

使用PHP腳本,我想搜索的第一列一個字符串(例如奔騰雙T3400),和(假設每個搜索只有一個結果,否則返回一個錯誤消息)創建一個包含第二列值的變量。

我不知道這是否會幫助,但我是那種希望它看起來有點像這樣:

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

其中$ cpuscore將包含搜索匹配的處理器名的成績查詢。

隨意建議一些會產生類似結果的東西。我有MySQL,但我沒有從CSV導入表的權限。

+0

['fgetscsv()'](http://php.net/fgetcsv)是啓動 – DaveRandom

+0

這可能會幫助你的地方:http://stackoverflow.com/a/12921943/ 1226894 – Baba

+0

您必須在循環中使用fgetcsv(),並在每個返回的行中搜索目標數據。這種方法的問題是速度很慢,並且直接取決於CSV文件的大小。如果可能的話,使用某種類型的數據庫會更好,但它們有更復雜的文本搜索和索引功能,結果會更快搜索 – GordonM

回答

0

我喜歡遍歷csv文件的每一行,找到我正在查找的單詞,並從那裏編譯結果。這裏的東西,讓你開始:

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

因爲他的CSV文件非常大,所以'file()'可以吃了很多的記憶。 「打開」會更好。 – Drahcir

+1

我用過這個。謝謝。 如果你想知道,下面是我完成的代碼。無論如何,這種方式都可以工作,並且總是返回第一個結果。 $ query =「Intel Core i7 3600M」 $ file = file('db.csv'); foreach($ file as $ value){ if(stristr($ value,$ query)){ \t $ items = explode(「,」,$ value); \t echo $ items [1]; \t}; }; – user1751197

1

您可以使用PHP函數fgetcsv()http://php.net/manual/en/function.fgetcsv.php按行遍歷CSV文件一行。例如:

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

}