簡體   English   中英

PHP Curl發送JSON數據

[英]PHP Curl Send JSON Data

我正在關注本教程: https : //lornajane.net/posts/2011/posting-json-data-with-php-curl

我想做的是通過CURL POST JSON數據

$url = "http://localhost/test/test1.php";  
$data = array("name" => "Hagrid", "age" => "36");

$data_string = json_encode($data);                                                                                                                     
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
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);
var_dump($result);

當我發布純文本數據時,我能夠接收到它,但是當我嘗試通過JSON時,我將無法接收到它。

這是我的test1.php

test1.php

print_r($_POST);
print_r($_POST);

任何幫助,將不勝感激。 謝謝

通過cURL POST JSON Data ,必須使用php://input 您可以像這樣使用它:

// get the raw POST data
$rawData = file_get_contents("php://input");

// this returns null if not valid json
return json_decode($rawData, true);  // will return array

php://input是一個只讀流,允許您從請求正文中讀取原始數據

PHP超全局$_POST只能包裝以下數據

  • application/x-www-form-urlencoded (用於簡單表單發布的標准內容類型)或
  • multipart/form-data-encoded (主要用於文件上傳)

現在的內容將是application/json (或至少沒有上述提到的內容),因此PHP的$_POST -wrapper不知道如何處理(還)。

參考

JSON數據不在$ _POST中通過。 您需要使用file_get_contents('php://input');

您還需要對其進行json_decode。

$json = json_decode(file_get_contents('php://input'));

var_dump($json);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM