我每天有两次通过ftp发送csv文件。我正在尝试编写一个php文件来打开这个文件,按类别列过滤它,删除没有特定术语/术语的行然后保存文件。
我已经尝试了很多互联网上发现的代码片段的变体,但是在我的生活中无法弄清楚如何让它发挥作用。
我尝试使用此问题中找到的代码变体,但无法在我的方案中使其正常工作
Filter a csv file by a word or text using php
如果它有助于我尝试编辑的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类别下有许多产品,也不会显示任何结果。
答案 0 :(得分:2)
我认为你在错误的专栏中搜索。 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);
答案 1 :(得分:0)
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&#39; / [0-9 /] [0-9] * $ / d&#39; FILENAME.TXT