【问题标题】:How to pass csv file as input through command line?如何通过命令行将csv文件作为输入传递?
【发布时间】: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


【解决方案1】:

首先,您必须定义您希望接受的选项,在这种情况下,我们只定义了选项“文件”。

$options = ['file:'];

然后当你执行你的脚本时:

php script.php --file=users.csv

您将收到您已经定义的所有选项。

$values = getopt(null, $options);

你会有这样的东西:

<?php 

require 'database.php';

$options = ['file:'];

$values = getopt(null, $options);

$lines = file($values['file'], FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);

// Rest of the script...

我建议您阅读getopt function 的文档,以帮助您理解和完成您的任务。

【讨论】:

  • 我试过这个我认为我的代码中有一些错误。它一遍又一遍地保持打印连接到数据库。
猜你喜欢
  • 2015-04-17
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
相关资源
最近更新 更多