简体   繁体   中英

Running PHP Script from terminal with parameters

I try to get parameters and run php script from terminal. If one of the parameters is not exists, I want to thrown an exception. I used getopt function. But I could not figure out how to thrown exception. And when I call the script

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

it's not working.

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

Could someone help me to figure out this.

Issues

  1. Passed long options arguments but trying to get short options https://www.php.net/manual/en/function.getopt.php
  2. Use = instead of : in the command
  3. Invalid variable syntax. missing $
  4. Incomplete logic

Command

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

Working Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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