Php 无法使用curl将动态数据从窗体传递到api
我有一个表单,我希望通过它捕获值,并将其以json格式传递到api中,为此我使用以下代码Php 无法使用curl将动态数据从窗体传递到api,php,json,api,curl,Php,Json,Api,Curl,我有一个表单,我希望通过它捕获值,并将其以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://exam
<?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);
?>
不要发明轮子。传递数据时使用json\u encode
:
$post_fields = array(
'name' => $name,
'location' => $location,
'age' => $age
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
我收到此错误:此异常已记录为id 73jbj3e8b。