在PHP中将CSV文件解析为MySQL数据库
我有一个大约350行的CSV文件,里面有各种各样的供应商,包括服装、工具、娱乐等。。类别。使用以下代码,我已经能够打印出我的CSV文件在PHP中将CSV文件解析为MySQL数据库,php,mysql,file-io,csv,Php,Mysql,File Io,Csv,我有一个大约350行的CSV文件,里面有各种各样的供应商,包括服装、工具、娱乐等。。类别。使用以下代码,我已经能够打印出我的CSV文件 <?php $fp = fopen('promo_catalog_expanded.csv', 'r'); echo '<tr><td>'; echo implode('</td><td>', fgetcsv($fp, 4096, ',')); echo '</td
<?php
$fp = fopen('promo_catalog_expanded.csv', 'r');
echo '<tr><td>';
echo implode('</td><td>', fgetcsv($fp, 4096, ','));
echo '</td></tr>';
while(!feof($fp)) {
list($cat, $var, $name, $var2, $web, $var3, $phone,$var4, $kw,$var5, $desc) = fgetcsv($fp, 4096);
echo '<tr><td>';
echo $cat. '</td><td>' . $name . '</td><td><a href="http://www.' . $web .'" target="_blank">' .$web.'</a></td><td>'.$phone.'</td><td>'.$kw.'</td><td>'.$desc.'</td>' ;
echo '</td></tr>';
}
fclose($file_handle);
show_source(__FILE__);
?>
需要注意的是,最后一行以两个逗号开头,因为它也列在“衣服”类别中
我担心CSV输出错误
我应该使用foreach循环而不是此列表方式吗?我应该先去掉任何不必要的空白列吗
请告知您可能发现的任何缺陷,以及我可以使用的改进,以便我可以准备将此数据导入MySQL数据库。我不确定您的CSV的整体结构-很难根据两行代码做出规则假设。。。但类似于以下的方法应该有效:
$fp = fopen('promo_catalog_expanded.csv', 'r');
// normalize the column names
$columns = array_change_key_case(fgetcsv($fp, 0, ','), CASE_LOWER);
$lastCategory = null;
while(false !== ($data = fgetcsv($fp, 0, ','))) {
$data = array_combine($columns, $data); // make it an assoc array
// test if category has a value - if it doesnt use the last category
if(empty($data['category']) && null !== $lastCategory ){
$data['category'] = $lastCategory;
}
// if we have started a new set of entries for a cat, we need to make it the $lastCategory
if($lastCategory !== $dataCategory && null !== $data['category']) {
$lastCategory = $data['category'];
}
// your sql to do the insert
}
您是否知道
加载数据填充
?有没有看过MySQLLOAD DATA
命令?我会让MySQL直接处理CSV,将所有内容移动到临时表中,并从那里更新您的真实数据。为什么要在PHP中编写额外的管道代码?负载数据的唯一问题是,如果他在服务器上实时执行此操作,他可能没有权限执行它。以前没有使用过负载数据,我将对此进行研究,谢谢。类别的末尾由一个空行指定,正如您在开始之前看到的:,,,,,,,,,,
谢谢你的代码,我会考虑修改它。
$fp = fopen('promo_catalog_expanded.csv', 'r');
// normalize the column names
$columns = array_change_key_case(fgetcsv($fp, 0, ','), CASE_LOWER);
$lastCategory = null;
while(false !== ($data = fgetcsv($fp, 0, ','))) {
$data = array_combine($columns, $data); // make it an assoc array
// test if category has a value - if it doesnt use the last category
if(empty($data['category']) && null !== $lastCategory ){
$data['category'] = $lastCategory;
}
// if we have started a new set of entries for a cat, we need to make it the $lastCategory
if($lastCategory !== $dataCategory && null !== $data['category']) {
$lastCategory = $data['category'];
}
// your sql to do the insert
}