【发布时间】:2021-02-09 15:07:55
【问题描述】:
我被分配了一项任务,但我不确定如何像在命令文件中那样传递 csv 文件,所以我在我的代码中对其进行了硬编码。但是,我仍然想学习如何做到这一点?任何帮助表示赞赏。
创建一个从命令行执行的 PHP 脚本,该脚本接受 CSV 文件作为输入 (参见下面的命令行指令)并处理 CSV 文件。解析的文件数据是 插入到 MySQL 数据库中。
The PHP script should include these command line options (directives):
• --file [csv file name] – this is the name of the CSV to be parsed
• --create_table – this will cause the MySQL users table to be built (and no further
• action will be taken)
• --dry_run – this will be used with the --file directive in case we want to run the
script but not insert into the DB. All other functions will be executed, but the
database won't be altered
• -u – MySQL username
• -p – MySQL password
• -h – MySQL host
• --help – which will output the above list of directives with details.
我所做的是将 csv 文件硬编码到我的 php 文件中。如何通过命令行接受 csv 文件作为输入?
我的代码:
<?php
require 'database.php';
$lines = file('users.csv', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$csv = array_map('str_getcsv', $lines);
$col_names = array_shift($csv);
$users = [];
$stmt = $dbh->prepare('INSERT INTO users (name, surname, email) VALUES (?,?,?)');
foreach($csv as $row) {
$users[] = [
$col_names[0] => ucfirst(strtolower($row[0])),
$col_names[1] => ucfirst(strtolower($row[1])),
$col_names[2] => strtolower(strtolower($row[2])),
];
}
foreach($users as $user) {
$stmt->execute($user);
}
?>
【问题讨论】:
-
@RamyHerrira 不幸的是,它没有显示任何 csv 文件示例
-
很抱歉,您不会总能找到问题的具体答案!在这里,您必须将 csv 文件的名称传递给您的脚本。在这种情况下,名称是“users.csv”,因此您可以像
php script.php --file=users.csv那样执行您的脚本。我刚刚向您展示的文章解释了如何使用函数getopt -
我明白了。但是,如果我这样传递它,我该如何更改我的代码,以便我可以在我的 php 脚本中使用该文件值? @RamyHerrira
标签: php sql database csv command