dongyi5425 2017-04-11 06:47
浏览 67

无法使用curl将表单中的Pass动态数据传递给api

I have a form through which i wish to capture values and pass it into api in json format for that i am using the following code.

<?php
$name = $this->input->post('name');
$location = $this->input->post('location');
$age = $this->input->post('age');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
    'name' => $name,
    'location' => $location,
    'age' => $age
}");

curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Apikey: ***";
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

print_r($http_status);

echo "<br>";

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

print_r($result);
?>

I am getting the following error

For http_status i am getting error

400

And for $result i am getting error

[Invalid Json: Unexpected character (''' (code 39)): was expecting double-quote to start field name at [Source: akka.util.ByteIterator$ByteArrayIterator$$anon$1@1a18f8fc; line: 3, column: 3]]

In order to resolve the above mentioned issue if i try to give double-quote then i am getting php syntax error

Can anyone please tell me how to send the data successfully

  • 写回答

1条回答 默认 最新

  • duandou9931 2017-04-11 06:50
    关注

    Don't invent the wheel. Use json_encode when passing data:

    $post_fields = array(
        'name' => $name,
        'location' => $location,
        'age' => $age
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题