[英]Filter a CSV file using php
我每天兩次通過ftp發送一個csv文件。 我正在嘗試編寫一個php文件來打開此文件,按類別列對其進行過濾,刪除其中沒有特定術語的行,然后保存文件。
我已經嘗試了許多在Internet上找到的代碼片段的變體,但是我一生都無法弄清楚如何使其工作。
我嘗試使用此問題中找到的代碼的變體,但無法使其在我的情況下起作用
如果有幫助CSV文件,我試圖編輯就設在這里: http://accurateav.co.uk/sahara/saharafeed.csv
<?php
$file = fopen('saharafeed.csv', 'r');
// You can use an array to store your search words, makes things more flexible.
// Supports any number of search words.
$words = array('casio');
// Make the search words safe to use in regex (escapes special characters)
$words = array_map('preg_quote', $words);
$regex = '/'.implode('|', $words).'/i';
while (($line = fgetcsv($file)) !== FALSE) {
list($ExportDate, $ItemCode, $Manufacturer, $Model, $ProductName, $DealerPrice, $Stock, $RRP, $Category, $ShortDesc, $LongDesc, $Weightkg, $EAN, $NonStock, $LargePictureURL, $SpecSheet, $HiResPhoto1, $HiResPhoto2) = $line;
if(preg_match($regex, $Category)) {
echo "$ExportDate, $ItemCode, $Manufacturer, $Model, $ProductName, $DealerPrice, $Stock, $RRP, $Category, $ShortDesc, $LongDesc, $Weightkg, $EAN, $NonStock, $LargePictureURL, $SpecSheet, $HiResPhoto1, $HiResPhoto2<br />\n";
}
}
?>
到目前為止,這是我用來過濾類別以僅顯示Casio類別中的產品的代碼,但是,即使在casio類別下有許多產品,當我運行腳本時也不會顯示任何結果。
我認為您在搜索錯誤的列。 casio
位於制造商列中。 您必須在那搜索。 考慮以下示例:
$i = 0;
$manufacturer_key = null;
$needles = array('casio', 'nec', 'hitachi');
$results = array();
$columns = array();
if(($handle = fopen('saharafeed.csv', 'r')) !== false) {
while(($data = fgetcsv($handle, 4096, ',')) !== false) {
if($i == 0) {
// sets the key where column to search
$columns = $data;
$i++; $manufacturer_key = array_search('Manufacturer', $data);
} else {
foreach($needles as $needle) {
if(stripos($data[$manufacturer_key], $needle) !== false) {
$results[] = $data;
}
}
}
}
fclose($handle);
}
array_unshift($results, $columns);
echo '<pre>';
print_r($results);
echo '</pre>';
casio
樣本輸出:
Array
(
[0] => Array
(
[0] => ExportDate
[1] => ItemCode
[2] => Manufacturer
[3] => Model
[4] => ProductName
[5] => DealerPrice
[6] => Stock
[7] => RRP
[8] => Category
[9] => ShortDesc
[10] => LongDesc
[11] => Weightkg
[12] => EAN
[13] => NonStock
[14] => LargePictureURL
[15] => SpecSheet
[16] => HiResPhoto1
[17] => HiResPhoto2
)
[1] => Array
(
[0] => 11/06/2014
[1] => 1610044
[2] => NEC
[3] => 60003221
[4] => NEC NP14ZL
[5] => 999
[6] => 0
[7] => 1348.65
[8] => Projectors Accessories
[9] => 2.97-4.79:1 Zoom Lens
[10] => Replacement 2.97–4.79:1 Zoom Lens compatible with the following products:
... and many more
將結果放回csv格式:
$fp = fopen('file.csv', 'w');
foreach ($results as $row) {
fputcsv($fp, $row);
}
fclose($fp);
Remove the line matching by a regular expression (by eliminating one containing digital characters, at least 1 digit, located at the end of the line):
sed'/ [0-9 /] [0-9] * $ / d'filename.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.