gpt4 book ai didi

php - 在 PHP 中将 CSV 文件解析到 MySQL DB

转载 作者:行者123 更新时间:2023-11-29 15:01:45 25 4
gpt4 key购买 nike

我有一个大约 350 行的 CSV 文件,其中包含属于服装、工具、娱乐等类别的各种供应商。使用以下代码我已经能够打印出我的 CSV 文件。

<?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__);
?>

您可能会注意到的第一件事是 list() 中的无关变量。这是因为 Excel 电子表格/csv 文件的方式:

Category,,Company Name,,Website,,Phone,,Keywords,,Description  
,,,,,,,,,,
Clothes,,4imprint,,4imprint.com,,877-466-7746,,"polos, jackets, coats, workwear, sweatshirts, hoodies, long sleeve, pullovers, t-shirts, tees, tshirts,",,An embroidery and apparel company based in Wisconsin.
,,Apollo Embroidery,,apolloemb.com,,1-800-982-2146,,"hats, caps, headwear, bags, totes, backpacks, blankets, embroidery",,An embroidery sales company based in California.

需要注意的一点是,最后一行以两个逗号开头,因为它也列在“服装”类别中。

我担心的是我的 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

}

关于php - 在 PHP 中将 CSV 文件解析到 MySQL DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2914006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com