Is there a PHP library that I can use to parse options and parameters in a command line php script? I do know the function getopt
, but is there something similar for parameters?
There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).
$argv — Array of arguments passed to script.
To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.
getopt
is a possibility but it's no fun, especially not if you're used to Python (or Ruby, which probably has similarly beautiful argv parsers). Here are some better alternatives, they probably all require PHP 5.3+.
I've tried Commando and I'm happy with it.
ConsoleKit would have been next in line.
php-cli-tools has some more functionality such as progress indicators and tabular displays. I only found it 10 minutes ago, since I want tabular display I might move to this library from Commando at some point.
Also check GetOptionKit as it can handle subcommands.
Use getopt
for options and the $argv
array for parameters - http://php.net/manual/en/reserved.variables.argv.php
also have a look at http://docs.php.net/manual/en/features.commandline.php for stuff like reading arguments from $argv
of the form --name=VALUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With