curl 的等效 php 选项



我正在尝试使用以下选项发送 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"
         }
       }'

换句话说,我知道如何使用...

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

但我不知道 -d 标志的等效项。

谢谢

它是需要随请求一起发送的数据

我通常将其包装到一个函数中,以使处理错误/成功更容易。特别是如果您正在处理像 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

但我不知道 -d 标志的等效项。

这是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'
        )
    ))
));

最新更新