我有一个表单,通过它我希望捕获值并将其传递给ji格式的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我收到错误
[无效的Json:意外的字符('''(代码39)):期待 双引号在[来源: akka.util.ByteIterator$ByteArrayIterator$$anon$1@1a18f8fc;行:3, 专栏:3]]
为了解决上述问题,如果我尝试给双引号,那么我得到php语法错误
任何人都可以告诉我如何成功发送数据
答案 0 :(得分:0)
不要发明轮子。传递数据时使用json_encode
:
$post_fields = array(
'name' => $name,
'location' => $location,
'age' => $age
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));