PHP cURL,POST JSON [英] PHP cURL, POST JSON

查看:115
本文介绍了PHP cURL,POST JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要POST以下JSON代码,但由于某种原因它不工作。下面是我的代码。

I need to POST the following JSON code, but for some reason it is not working. Below is the code that I have.

$fieldString = "395609399";
//the curl request processor
function processCurlJsonrequest($URL, $fieldString) { //Initiate cURL request and send back the result
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    if ($fieldCount) { // in case of post fields present then pass it on
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{categoryId: $fieldString}"));
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    $resulta = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
    }
    return $resulta;
}

这是调用cURL请求的函数:

Here is the function which calls the cURL request:

function get_cat($categoryId, $URL) {
    $fields = array(
        "categoryId" => $categoryId
    );
    $fields_string = $fields;
    return $this->processCurlJsonrequest($URL, $fields_string);
}


推荐答案

是:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{categoryId: $fieldString}"));

CURLOPT_POSTFIELDS将接受一个参数数组或一个URL编码的参数字符串:

CURLOPT_POSTFIELDS will accept either an array of parameters, or a URL-encoded string of parameters:

curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>json_encode($stuff)));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.urlencode(json_encode($stuff)));

其中 json POST字段(即:将导致 $ _ POST ['json'] 可访问)。

Where json will be the name of the POST field (i.e.: will result in $_POST['json'] being accessible).

这篇关于PHP cURL,POST JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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