PHP使用curl提交json格式数据

$params = array();
foreach ($_POST as $key => $value) {
    $params[$key] = $value;
}

echo request_post($url, $params);

function request_post($url = '', $params = '', $timeout = 5000)
{
    if (empty($url) || empty($params)) {
        return '{}';
    }

    $header = array(
        "Accept: application/json",
        "Content-Type: application/json",
    );

    $jsonData = json_encode($params);
    $postUrl = $url;
    $ch = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false);
    $data = curl_exec($ch);//运行curl
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $response = array();

    $response['httpCode'] = $httpCode;
    $response['data'] = json_decode($data);

    return json_encode($response);
}

function request_get($url = '', $params = '', $timeout = 5000)
{
    if (empty($url) || empty($params)) {
        return '{}';
    }

    $header = array(
        "Accept: application/json",
        //"Content-Type: application/json",
    );

    $linkedData = buildLinkedParams($params);
    $getUrl = $url . '?' . $linkedData;

    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $getUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false);
    $data = curl_exec($ch);//运行curl
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $response = array();

    $response['httpCode'] = $httpCode;
    $response['data'] = json_decode($data);

    return json_encode($response);
}

/**
 * 拼接参数:key1=value1&key2=value2
 * @param $params
 * return
 */
function buildLinkedParams($params)
{
    $str = "";
    while (list ($key, $val) = each ($params)) {
        $str .= $key . "=" . $val . "&";
    }
    //去除最后&符
    $str = substr($str, 0, count($str)-2);
    //去除转义符
    if (get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return $str;
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/19/php-curl-post-json/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
PHP使用curl提交json格式数据
$params = array(); foreach ($_POST as $key => $value) { $params[$key] = $value; } echo request_post($url, $params); function request_post($……
<<上一篇
下一篇>>
文章目录
关闭
目 录