如何使用CURL向API发送数据或从API接收数据? [英] How to send and receive data to/from an API using CURL?

查看:402
本文介绍了如何使用CURL向API发送数据或从API接收数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做一个API.为此,我将使用POST以JSON的形式从移动设备接收数据.我必须处理这些数据,并将响应也以JSON的形式发送回设备. 但是我不知道如何获取将要接收的数据.我尝试使用CURL进行一些测试,以查看如何获取此数据,但$_POST始终为空.能否请您告诉我如何使用CURL将数据以JSON格式发送到API,以及如何接收此数据,以便可以使用它并将其作为响应发送回去?

I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON. But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?

这些是我的测试文件:

curl.php:

curl.php:

    //set POST variables
    $url = 'http://test.dev/test.php';
    $data = array(
        'fname' => 'Test',
        'lname' => 'TestL',
        'test' => array(
            'first' => 'TestFirst',
            'second' => 'TestSecond'
        )
    );

    //open connection
    $ch = curl_init($url);

    $json_data = json_encode($data);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($json_data))
    );

    // execute post
    $result = curl_exec($ch);

    echo $result;

    //close connection
    curl_close($ch);

test.php:

test.php:

var_dump($_POST);

我得到的答复是:

array(0) { }

推荐答案

您需要将POST数据作为URL查询字符串或数组传递,问题是您以JSON格式发布数据,但PHP无法解析JSON自动,因此$_POST数组为空.如果需要,您需要在test.php中自己解析:

You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:

$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);

相同的问题: 1 2

这篇关于如何使用CURL向API发送数据或从API接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆