Parsing Command Line Arguments in PHP
Most of us have know PHP as a language used for web development, but it is also being used for writing backend processing scripts, backup scripts, deferred processing scripts etc. for a long time but still not as much as other scripting languages as Perl, Python, or Ruby. But if you are a PHP developer, why not use your PHP knowledge to write scripts for which you otherwise would have use another language.
Here we would be looking at how to read command line arguments in a PHP script, you can refer to these articles for more knowledge about command line arguments Command Line Arguments, Reading Command Line Arguments in Python.
The PHP interpreter automatically collects the command line arguments passed by the user via the shell, and stores it in a special array variable $argv, these contain the arguments in the order they were passed, the first one always being the command/script filename executed.
Follow the example below,
Now, let us look at how to parse command line arguments as the professional programs do, where order of the options do no matter, arguments can be passed in name-value pairs. For this purpose we'll be using a PEAR package Console_GetoptPlus, it is really customizable and easy to use. Follow the code below, which is quite self-explanatory.
As you can see, the configuration is easy and understandable, and so it the parsed array.
|All times are GMT +5.5. The time now is 11:38.|