如何在PHP CURL请求中保留Integer

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何在PHP CURL请求中保留Integer脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用API​​,当我向他们发送POST请求时,他们会发出一个警告,即数组中的一个字段必须是integer类型,而不是String类型.

我的CURL设置是这样的:

$post_fields = array(
            'data_source_uuid' => $uuid,'name' => 'testPlan','interval_count' => 1,'interval_unIT' => 'month','external_id' => 'Eur_fees'
        );
    $curl = curl_init();
    curl_setopt_array($curl,array(
        CURLOPT_RETURNtransfer => true,CURLOPT_URL => $url,CURLOPT_USERPWD => $api_key
        CURLOPT_POSTFIELDS =>  $post_fields,CURLOPT_HTTPHEADER => 'Content-tyPE: application/json'
    ));
    $result = curl_exec($curl);
    curl_close( $curl );

当我将它发送到我的localhost和var_dump上的另一个URL时,我得到了这个:

string(253) "array(5) {
          ["data_source_uuid"]=>
          string(39) "uuid"
          ["name"]=>
          string(8) "TestPlan"
          ["interval_count"]=>
          string(1) "1"
          ["interval_unit"]=>
          string(5) "month"
          ["external_id"]=>
          string(8) "Eur_fees"
        }"

这里的问题是interval_count是一个String而不是一个Integer.如果我在使用CURLOPT_POSTFIELDS之前使用VAR_dump它是一个整数,那么CURL部分中的某些内容正在改变它,但我不确定是什么.

该API适用于名为chartmogul.COM的网站

解决方法

来自ChartMogul的Bill.您需要使用json_encode($data)对数据进行编码.另请确保您的数据UUID,帐户密钥和帐户令牌正确无误.以下请求适用于我:

<?PHP 

// account variables
$ds_uuid = "DATA_SOURCE_UUID";
$token = 'API_TOKEN';
$password = 'SECRET_KEY';

// request url
$baseurl='https://api.chartmogul.com/v1/';
$url=$baseurl.'import/plans';

// data to be posted
$post_fields = array(
            'data_source_uuid' => "$ds_uuid",'name' => 'A plan','external_id' => 'eur_fees'
        );

// encode JSON data
$data = json_encode($post_fields);

// initialize cURL
$ch = curl_init();

// set options
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_USERPWD,"$token:$password");
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch,CURLOPT_POST,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
    'Content-Type: application/json','Content-Length: ' . strlen($data))
);

// make the request
$result = curl_exec($ch);

// decode the result
$json = json_decode($result,true);

// PRint the result
print $json;

curl_close($ch);
?>`enter code here`

脚本宝典总结

以上是脚本宝典为你收集整理的如何在PHP CURL请求中保留Integer全部内容,希望文章能够帮你解决如何在PHP CURL请求中保留Integer所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。