我正在尝试将 json 数据作为参数传递给 cURL POST。但是,我坚持捕获它并将其保存在数据库上。
curl 文件:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl
test_curl 文件:
$order_info = $_POST; // this seems to not returning anything
//SAVE TO DB... saving empty...
我错过了什么?呜....
最佳答案
您在正文中将数据作为原始 JSON 发送,它不会填充 $_POST
变量。
您需要做以下两件事之一:
- 您可以将内容类型更改为将填充
$_POST
数组的类型 - 您可以阅读原始 body 数据。
如果您可以控制通信的两端,我会推荐选项二,因为它将请求正文大小保持在最低限度并随着时间的推移节省带宽。 (编辑:我在这里并没有真正强调它将节省的带宽量可以忽略不计,每个请求只有几个字节,这只在非常高流量的环境中才是有效的关注点。但是我仍然推荐选项二因为这是最干净的方式)
在您的 test_curl
文件中,执行以下操作:
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
$postedJson = json_decode($rawData);
var_dump($postedJson);
如果要填充 $_POST
变量,您需要更改将数据发送到服务器的方式:
$data = array (
'name' => 'Hagrid',
'age' => '36'
);
$bodyData = array (
'json' => json_encode($data)
);
$bodyStr = http_build_query($bodyData);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($bodyStr)
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);
$result = curl_exec($ch);
原始的、未解码的 JSON 现在将在 $_POST['json']
中可用。
关于php - 通过 CURL 发布 JSON 数据并抓取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9062060/