繁体   English   中英

从带有参数的终端运行 PHP 脚本

[英]Running PHP Script from terminal with parameters

我尝试获取参数并从终端运行 php 脚本。 如果其中一个参数不存在,我想抛出一个异常。 我使用了 getopt function。 但我不知道如何抛出异常。 当我调用脚本时

php myscript.php --file: file1.csv --unique-combinations: file2.csv

它不工作。

<?php
$files = getopt("file:unique-combinations:");

if(!files["file"]) {
    echo "Please provide a CSV file with parameter file";
} else if(!files["unique-combinations"]) {
    echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
    $datas = array_count_values(file(files["file"]));
    $fp = fopen(files["unique-combinations"], 'w');

    foreach($datas as $data => $value) {
        fputcsv($fp, $data);
    }
    fclose($fp);
}
?>

有人可以帮我弄清楚这一点。

问题

  1. 通过了多头期权 arguments 但试图获得空头期权https://www.php.net/manual/en/function.getopt.php
  2. 在命令中使用=而不是:
  3. 变量语法无效。 缺少$
  4. 不完整的逻辑

命令

php myscript.php --file=file1.csv --unique-combinations=file2.csv

工作代码

<?php
$files = getopt("", ["file:", "unique-combinations:"]);

if (!isset($files["file"])) {
    echo "Please provide a CSV file with parameter file";
} else if (!isset($files["unique-combinations"])) {
    echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
    $datas = array_count_values(file($files["file"]));;
    $fp = fopen($files["unique-combinations"], 'w');

    foreach ($datas as $data => $value) {
        fputcsv($fp, explode(',', trim($data)));
    }
    fclose($fp);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM