PHP 将变量插入字符串中以供发布请求


PHP insert variables into string for post request

当我只有一个$json变量的字符串时,我的函数可以工作,但当我尝试将值作为变量插入时,我的函数不起作用。不确定问题是什么。这是我的代码:

  $myAPIKey = "apikey";
  $command = "campaignstats";
  $id = "9000";
  $date = "2016-01-11";
  $groupby = "domain";
  function call($apiKey, $cmd, $dt, $i, $gpby) {
    $url = "http://data.company.net/auth";
    // $json = '{"command" : "campaignstats",
    //           "date" : "2016-01-11",
    //           "id" : "9000",
    //           "groupby" : "domain"}';
    $json = '{"command" : '.$cmd.',
              "date" : '.$dt.',
              "id" : '.$i.',
              "groupby" : '.$gpby.'}';
    $sAPIKey = auth($apiKey);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$json.'&sapi_key='.$sAPIKey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $raw_output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($raw_output, true);
  }
call($myAPIKey, $command, $id, $date, $groupby);

使用 json_encode ,从所需的数据构建数组。

$json = [
        'command'   => $cmd,
        'data'      => $dt,
        'id'        => $i,
        'groupby'   => $gpby
         ];
$data = json_encode($json);

然后传递到帖子字段

curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$data.'&sapi_key='.$sAPIKey);

编辑您的调用函数,例如顺序$date将是第三位置,$id将是第四位置。

call($myAPIKey, $command, $date, $id, $groupby);

您可以使用 json_encode ,只需从您拥有的数据构建一个关联数组即可。

$data = [
    'command'   => $cmd,
    'data'      => $dt,
    'id'        => $i,
    'groupby'   => $gpby
];
$string = json_encode($data);

然后将其作为帖子字段的值传递

curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$string.'&sapi_key='.$sAPIKey);