PHP,将参数从命令行传递到 PHP 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11048835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:39:54  来源:igfitidea点击:

PHP, pass parameters from command line to a PHP script

phpparameter-passingcommand-line-interface

提问by 125369

I want to pass parameters from PHP Command Line Interface, and then read in the values using PHP script, something like this:

我想从 PHP 命令行界面传递参数,然后使用 PHP 脚本读取值,如下所示:

<?php
  $name1 = $argv[1];    
  echo $name1;
?>

I pass the variable from CLI like this:

我像这样从 CLI 传递变量:

C:\xampp\php\php.exe name.php Robby

The above works, I get Robby as the output.

以上工作,我得到罗比作为输出。

But I want to do something like this:

但我想做这样的事情:

C:\xampp\php\php.exe name.php -inputFirstName="Robby"

So that the user is well informed to enter the correct parameters in the correct places. What is the appropriate way to parse these parameters?

以便用户充分了解在正确的位置输入正确的参数。解析这些参数的合适方法是什么?

回答by vascowhite

When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:

从命令行调用 PHP 脚本时,您可以使用 $argc 来找出传递了多少参数,并使用 $argv 来访问它们。例如运行以下脚本:

<?php
    var_dump($argc); //number of arguments passed 
    var_dump($argv); //the arguments passed
?>

Like this:-

像这样:-

php script.php arg1 arg2 arg3

Will give the following output

将给出以下输出

int(4)
array(4) {
  [0]=>
  string(21) "d:\Scripts\script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

See $argvand $argcfor further details.

有关更多详细信息,请参阅$argv$argc

To do what you want, lets say

做你想做的,让我们说

php script.php arg1=4

You would need to explode the argument on the equals sign:-

您需要在等号上分解参数:-

list($key, $val) = explode('=', $argv[1]);
var_dump(array($key=>$val));

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.

这样你就可以在等号前面放任何你想要的东西而不必解析它,只需检查 key=>value 对是否正确。然而,这有点浪费,只是指示用户以正确的顺序传递参数。

回答by NickM

I use this fairly concise method:

我使用这个相当简洁的方法:

if($argc>1)
  parse_str(implode('&',array_slice($argv, 1)), $_GET);

Which would handle a call such as:

它将处理诸如以下的呼叫:

php script.php item1=4 item2=300

By sending it into $_GET you automatically handle web or CLI access.

通过将其发送到 $_GET,您可以自动处理 Web 或 CLI 访问。

For commentary, this is doing the following:

对于评论,这是在执行以下操作:

  • If the count of arguments is greater than one (as first item is the name of the script) the proceed
  • Grab the arguments array excluding first item
  • Turn it into a standard query string format with ampersands
  • use parse_str to extract to the $_GET array
  • 如果参数的数量大于一个(因为第一项是脚本的名称),则继续
  • 获取不包括第一项的参数数组
  • 将其转换为带有 & 符号的标准查询字符串格式
  • 使用 parse_str 提取到 $_GET 数组

回答by Konrad Neuwirth

While the answer is correct and you could do the parsing by hand, PHP also offers the getopt()function that might actually provide useful here.

虽然答案是正确的并且您可以手动进行解析,但 PHP 还提供了getopt()可能在此处实际提供有用的功能。

There's also object-oriented alternatives (written in PHP, available in a number of libraries) that might turn out to be what you need. Googling for "php getopt" will yield helpful results.

还有一些面向对象的替代方案(用 PHP 编写,可在许多库中使用)可能正是您所需要的。谷歌搜索“php getopt”会产生有用的结果。

回答by bnp887

The getopt()function is probably the most correct answer in the case of the question. Especially since it was made platform independent with PHP 5.3. In the particular case of this question and parsing multiple parameters, one way to leverage this function would be as follows:

getopt()功能可能是问题的情况下,最正确的答案。特别是因为它与 PHP 5.3 平台无关。在这个问题和解析多个参数的特殊情况下,利用这个函数的一种方法如下:

$defaultValues = array("inputFirstName" => "");
$givenArguments = getopt("", array("inputFirstName:"));
$options = array_merge($defaultValues, $givenArguments);
$inputFirstName = $options['inputFirstName'];

The call to set $inputFirstName with the value "Robby" would be:

使用值“Robby”设置 $inputFirstName 的调用将是:

> php script.php --inputFirstName="Robby"

Explanation

解释

Default values for all expected parameters are set in the $defaultValuesarray. Input sent through via command line arguments are collected by PHP's getoptfunction and stored by the $givenArguments. Note that the colon (:) at the end of the "inputFirstName:"string indicates that this is a required argument. Without a colon here, only the presence of the argument would be detected, not the actual value (more information in the PHP Manual). Merging these two arrays together on the third line results in array with all expected parameters being set with either default values or arguments provided from the command line/terminal if they are available.

所有预期参数的默认值都在$defaultValues数组中设置。通过命令行参数发送的输入由 PHP 的getopt函数收集并由$givenArguments. 请注意,字符串:末尾的冒号 ( )"inputFirstName:"表示这是必需的参数。如果这里没有冒号,只会检测到参数的存在,而不是实际值(更多信息在 PHP 手册中)。在第三行将这两个数组合并在一起会导致数组的所有预期参数设置为默认值或从命令行/终端提供的参数(如果可用)。

回答by Gijs de Jong

If you don't mind using a library, I suggest you take a look at The Console Component by Symfony.

如果您不介意使用库,我建议您查看Symfony 的 The Console Component

It can be used to create command line applications and supports the use of Arguments & Options.

它可用于创建命令行应用程序并支持使用Arguments & Options

The documentation page contains a couple of excellent examples to get you started.

文档页面包含几个很好的示例来帮助您入门。

Of course under the hood it uses the same techniques as explained by vascowhite.

当然,它使用了与 vascowhite 解释的相同的技术。

回答by Mas

you can send parameters as one argument then parse that argument like a $_GET array

您可以将参数作为一个参数发送,然后像 $_GET 数组一样解析该参数

C:\xampp\php\php.exe name.php "inputFirstName=Robby&LastName=John"

and in your PHP file

并在您的 PHP 文件中

if (!empty($argv[1])) {
  parse_str($argv[1], $_GET);
}

you'll get arguments in $_GET array like usual

你会像往常一样在 $_GET 数组中得到参数

回答by álvaro

You can parse the user input on your program looking for specific strings such as -inputFirstName="x"(using regular expressions, for example) and then set the correct variable to x.

您可以解析程序中的用户输入以查找特定字符串,例如-inputFirstName="x"(例如使用正则表达式),然后将正确的变量设置为 x。