[英]Consuming an API using CURL in php
I am trying to consume an API, and anytime I send the data to the API, I get a "No data sent" response from the API.我正在尝试使用 API,每当我将数据发送到 API 时,我都会收到来自 API 的“未发送数据”响应。 below is my code.下面是我的代码。
<?php
$url = 'endpoint';
$curl = curl_init();
$valu = array(
'username' => 'used',
'firstname' => 'user',
'email' => 'user@email.com',
'bio' => 'A very good personality',
'lastname' => 'demo',
'password' => 'date'
);
$json_string = json_encode(array( "data" => $valu));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec($curl);
if($data){
echo $data;
}
curl_close($curl);
?>
below is data the API requires from the client以下是 API 需要客户提供的数据
{
"username":"username",
"firstname":"firstname",
"email":"email",
"bio":"A very good personality",
"lastname":"lastname",
"password":"data"
}
inside a node called 'data'在一个名为“数据”的节点内
Please, help请帮忙
I am providing with example, it worked for me!我提供了例子,它对我有用!
<?php
$url = 'https://reqres.in/api/users';
$curl = curl_init($url);-> this line is incorrect
$valu = array(
'name' => 'used',
'job' => 'user'
);
$json_string = json_encode(array( "data" => $valu));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec($curl);
if($data){
echo $data;
}
curl_close($curl);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.