简体   繁体   English

curl的等效php选项

[英]Equivalent php options for curl

I am trying to send a curl request with the following options, but I do not know how to send the data with the -d option in the php curl setup. 我正在尝试使用以下选项发送curl请求,但我不知道如何在php curl设置中使用-d选项发送数据。

curl -X 'POST' \
     -H 'Content-Type: application/json; charset=utf-8' \
     -H 'Authorization: Bearer x'
     -v 'URL' \
     -d
      '{
         "input": {
           "urn": "num",
           "compressedUrn": true,
           "rootFilename": "A5.iam"
         }
       }'

In other words, I know how to send the header using ... 换句话说,我知道如何使用...发送标题

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer x'
    ));

But I do not know the equivalent for the -d flag. 但我不知道-d标志的等价物。

Thanks 谢谢

Its the data that needs to be sent with the request 它是需要随请求一起发送的数据

I normally wrap this into a function to make handling errors / success easier. 我通常将其包装成一个函数,以使处理错误/成功更容易。 Especially if you are dealing with an API like paypal or something 特别是如果你正在处理像paypal或类似的API

// create the object (you can do this via a string if you want just remove the json encode from the postfields )

$request = new stdClass(); //create a new object
$request->input = new stdClass(); // create input object
$request->input->urn = 'num'; // assign values
$request->input->compressedUrn = true;
$request->input->rootFilename = 'A5.iam';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'URL HERE');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $request ) ); // encode the object to be sent
curl_setopt($ch, CURLOPT_POST, true); // set post to true        
curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [  //set headers
    'Content-Type: application/json',
    'Authorization: Bearer x'
]);
$result = curl_exec ($ch);
if ( ! $result) { //check if the cURL was successful.
    // do something else if cURL fails
}

curl_close ($ch);

$return = json_decode( $result ); // object if expecting json return

But I do not know the equivalent for the -d flag. 但我不知道-d标志的等价物。

it's CURLOPT_POSTFIELDS. 这是CURLOPT_POSTFIELDS。

curl_setopt_array($ch, array(
    CURLOPT_URL => 'URL',
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer x',
        'Content-Type: application/json; charset=utf-8'
    ),
    CURLOPT_POSTFIELDS => json_encode(array(
        'input' => array(
            'urn' => 'num',
            'compressedUrn' => true,
            'rootFilename' => 'A5.iam'
        )
    ))
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM