是否可以将数组作为命令行参数传递给 PHP 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2872755/
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-25 07:59:44  来源:igfitidea点击:

Is it possible to pass an array as a command line argument to a PHP script?

phpcommand-line

提问by Manos Dilaverakis

I'm maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I've just fixed a bug that would not allow it to fetch array variables from POST and GET and I'm wondering whether this is also applicable to the part that deals with the command line.

我正在维护一个 PHP 库,负责获取和存储传入数据(POST、GET、命令行参数等)。我刚刚修复了一个不允许它从 POST 和 GET 获取数组变量的错误,我想知道这是否也适用于处理命令行的部分。

Can you pass an array as a command line argument to PHP?

您可以将数组作为命令行参数传递给 PHP 吗?

采纳答案by dev-null-dweller

Directly not, all arguments passed in command line are strings, but you can use query string as one argument to pass all variables with their names:

直接不是,命令行中传递的所有参数都是字符串,但是您可以使用查询字符串作为一个参数来传递所有变量及其名称:

php myscript.php a[]=1&a[]=2.2&a[b]=c

<?php
parse_str($argv[1]);
var_dump($a);
?>

/*
array(3) {
  [0]=> string(1) "1"
  [1]=> string(3) "2.2"
  ["b"]=>string(1) "c"
}
*/

回答by Dal Hundal

Strictly speaking, no. However you could pass a serialized (either using PHP's serialize()and unserialize()or using json) array as an argument, so long as the script deserializes it.

严格来说,没有。但是,您可以将序列化的(使用 PHPserialize()unserialize()或使用 json)数组作为参数传递,只要脚本对其进行反序列化即可。

something like

就像是

php MyScript.php "{'colors':{'red','blue','yellow'},'fruits':{'apple','pear','banana'}}"

I dont think this is ideal however, I'd suggest you think of a different way of tackling whatever problem you're trying to address.

但是,我认为这并不理想,我建议您想出一种不同的方式来解决您要解决的任何问题。

回答by Victor

As it was said you can use serialize to pass arrays and other data to command line.

如前所述,您可以使用序列化将数组和其他数据传递到命令行。

shell_exec('php myScript.php '.escapeshellarg(serialize($myArray)));

And in myScript.php:

在 myScript.php 中:

$myArray = unserialize($argv[1]);

回答by pondix

The following code block will do it passing the array as a set of comma separated values:

以下代码块会将数组作为一组逗号分隔值传递:

<?php
  $i_array = explode(',',$argv[1]);
  var_dump($i_array);
?>

OUTPUT:

输出:

php ./array_play.php 1,2,3

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

回答by Rashmi Jain

In case, if you are executing command line script with arguments through code then the best thing is to base encode it -

如果您通过代码执行带有参数的命令行脚本,那么最好的办法是对其进行基本编码 -

base64_encode(json_encode($arr));

while sending and decode it while receiving in other script.

在发送和解码它的同时在其他脚本中接收。

json_decode(base64_decode($argv[1]));

That will also solve the issue of json receiving without quotes around the keys and values. Because without quotes, it is considered to be as bad jsonand you will not be able to decode that.

这也将解决在键和值周围没有引号的 json 接收问题。因为没有引号,它被认为是糟糕的 json,您将无法对其进行解码。

回答by Adam

Sort of.

有点。

If you pass something like this:

如果你通过这样的事情:

$php script.php --opt1={'element1':'value1','element2':'value2'}

You get this in the opt1 argument:

你在 opt1 参数中得到这个:

Array(
 [0] => 'element1:value1'
 [1] => 'element2:value2'
)

so you can convert that using this snippet:

所以你可以使用这个片段来转换它:

foreach($opt1 as $element){
    $element = explode(':', $element);
    $real_opt1[$element[0]] = $element[1];
}

which turns it into this:

这把它变成了这个:

Array(
 [element1] => 'value1'
 [element2] => 'value2'
)

回答by Salman A

You need to figure out some way of encoding your array as a string. Then you can pass this string to PHP CLI as a command line argument and later decode that string.

您需要找出将数组编码为字符串的某种方法。然后,您可以将此字符串作为命令行参数传递给 PHP CLI,然后对该字符串进行解码。

回答by Paul

After following the set of instructions below you can make a call like this:

按照下面的一组说明操作后,您可以像这样拨打电话:

phpcl yourscript.php _GET='{ "key1": "val1", "key2": "val2" }'

phpcl yourscript.php _GET='{ "key1": "val1", "key2": "val2" }'

To get this working you need code to execute before the script being called. I use a bash shell on linux and in my .bashrc file I set the command line interface to make the php ini flag auto_prepend_file load my command line bootstrap file (this file should be found somewhere in your php_include_path):

要使其正常工作,您需要在调用脚本之前执行代码。我在 linux 上使用 bash shell,在我的 .bashrc 文件中,我设置了命令行界面以使 php ini 标志 auto_prepend_file 加载我的命令行引导程序文件(该文件应该在您的 php_include_path 中的某个位置):

alias phpcl='php -d auto_prepend_file="system/bootstrap/command_line.php"'

This means that each call from the command line will execute this file before running the script that you call. auto_prepend_file is a great way to bootstrap your system, I use it in my standard php.ini to set my final exception and error handlers at a system level. Setting this command line auto_prepend_file overrides my normal setting and I choose to just handle command line arguments so that I can set $_GET or $_POST. Here is the file I prepend:

这意味着来自命令行的每次调用都将在运行您调用的脚本之前执行此文件。auto_prepend_file 是引导系统的好方法,我在我的标准 php.ini 中使用它在系统级别设置我的最终异常和错误处理程序。设置这个命令行 auto_prepend_file 会覆盖我的正常设置,我选择只处理命令行参数,以便我可以设置 $_GET 或 $_POST。这是我预先添加的文件:

<?php
// Parse the variables given to a command line script as Query Strings of JSON.
// Variables can be passed as separate arguments or as part of a query string:
//    _GET='{ "key1": "val1", "key2": "val2" }' foo='"bar"'
// OR
//    _GET='{ "key1": "val1", "key2": "val2" }'\&foo='"bar"' 
if ($argc > 1)
{
   $parsedArgs = array(); 

   for ($i = 1; $i < $argc; $i++)
   {
      parse_str($argv[$i], $parsedArgs[$i]);
   }

   foreach ($parsedArgs as $arg)
   {
      foreach ($arg as $key => $val)
      {
         // Set the global variable of name $key to the json decoded value.
         $$key = json_decode($val, true);
      }
   }

   unset($parsedArgs);
}
?>

It loops through all arguments passed and sets global variables using variable variables(note the $$). The manual page does say that variable variables doesn't work with superglobals, but it seems to work for me with $_GET (I'm guessing it works with POST too). I choose to pass the values in as JSON. The return value of json_decode will be NULL on error, you should do error checking on the decode if you need it.

它遍历所有传递的参数并使用变量变量(注意 $$)设置全局变量。手册页确实说变量变量不适用于超全局变量,但它似乎适用于 $_GET (我猜它也适用于 POST)。我选择将值作为 JSON 传递。json_decode 的返回值在出错时将为 NULL,如果需要,您应该对解码进行错误检查。

回答by Mwayi

So if a CLI is as such

因此,如果 CLI 是这样的

php path\to\script.php param1=no+array param2[]=is+array param2[]=of+two

Then the function thats reads this can be

那么读取 this 的函数可以是

function getArguments($args){
    unset($args[0]); //remove the path to script variable
    $string = implode('&',$args);
    parse_str($string, $params);
    return $params;
}

This would give you

这会给你

Array
(
    [param1] => no array
    [param2] => Array
             (
                 [0] => is array
                 [1] => of two
             )
)