php 通過curl post發送json資料執行個體_PHP教程

來源:互聯網
上載者:User
利用php curl發送json資料與curl post其它資料是一樣的,下面我來給大家總結幾個關於curl post發送json資料執行個體,希望能加深各位對curl post json資料的理解吧。

例1

代碼如下 複製代碼

$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);

$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);

例2

代碼如下 複製代碼

function http_post_data($url, $data_string) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();

$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array($return_code, $return_content);
}

$url = "http://xx.xx.cn";
$data = json_encode(array('a'=>1, 'b'=>2));

list($return_code, $return_content) = http_post_data($url, $data);

例3

代碼如下 複製代碼

$data=' {
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":"歌手簡介",
"key":"V1001_TODAY_SINGER"
},
{
"name":"菜單",
"sub_button":[
{
"type":"click",
"name":"hello word",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"贊一下我們",
"key":"V1001_GOOD"
}]
}]
}';

$ch = curl_init($urlcon); //請求的URL地址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//$data JSON類型字串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
$data = curl_exec($ch);
print_r($data);//建立成功返回:{"errcode":0,"errmsg":"ok"}

小結,我們發現最核心的一句代碼就是Content-Type: application/json;這個是檔案格式類型了。

http://www.bkjia.com/PHPjc/633132.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633132.htmlTechArticle利用php curl發送json資料與curl post其它資料是一樣的,下面我來給大家總結幾個關於curl post發送json資料執行個體,希望能加深各位對curl post json數...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.