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
=
instead of :
in the command$
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.