首页 文章

PHP cURL POST数据集

提问于
浏览
0

我已经获得了以下示例,以便将数据发布到API网址

curl --request POST \
  --url https://apiurl \
  --header 'auth-token: {{token}}' \
  --header 'content-type: application/json' \
  --data '{
  "user": {
    "email": "my@email.com",
    "name": "James",
    "tel": "0000000"
  }
}'

我使用以下代码让我的cURL工作,但我需要发布上面的用户参数,如电子邮件,名称,电话等 .

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => array('Cache-Control: no-cache', 'auth-token: '.$token)

));
$response = curl_exec($curl);
curl_close($curl);

如何使用我的代码发布字段作为示例状态?

2 回答

  • 0

    我用这种方式:

    <?php
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, array(
        'data'      => '{
      "user": {
        "email": "my@email.com",
        "name": "James",
        "tel": "0000000"
      }
    }'    
    ));
    $dados = curl_exec($handle);
    curl_close($handle);
    echo "$dados";
    ?>
    
  • -1

    这已在这里得到解答:How to POST JSON Data With PHP cURL?

    您只需要添加如下内容:

    $payload = json_encode(['user'=> ['email'=>'test@example.com','name'=>'Joe','tel'=>'123e332']] );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, $payload );
    curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    

相关问题