【问题标题】:Not able to pass Pass dynamic data from a form to api using curl无法使用 curl 将动态数据从表单传递到 api
【发布时间】:2017-04-11 06:47:12
【问题描述】:

我有一个表单,我希望通过该表单捕获值并将其以 json 格式传递给 api,因为我正在使用以下代码。

<?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);
?>

我收到以下错误

对于 http_status 我收到错误

400

对于 $result 我得到错误

[Invalid Json: Unexpected character (''' (code 39)): 期待 双引号在 [来源: akka.util.ByteIterator$ByteArrayIterator$$anon$1@1a18f8fc;线:3, 列:3]]

为了解决上述问题,如果我尝试给出双引号,那么我会收到 php 语法错误

谁能告诉我如何成功发送数据

【问题讨论】:

    标签: php json api curl


    【解决方案1】:

    不要发明轮子。传递数据时使用json_encode

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

    【讨论】:

    • 我收到此错误:此异常已使用 id 73jbj3e8b 记录。
    猜你喜欢
    • 2020-11-25
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多