使用 PHP cURL 发布 JSON 数据
Posting JSON Data With PHP cURL
情况
- 我想使用 php cURL post JSON 数据到我的 url
http://localhost/api_v2/url?key=***
这是我试过的
POST function
public function post(){
$ch = curl_init("http://localhost/api_v2/url?key=***");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$file_name = 'inventory.csv';
$file_path = 'C:\QuickBooks\'.$file_name;
$csv= file_get_contents($file_path);
$utf8_csv = utf8_encode($csv);
$array = array_map("str_getcsv", explode("\n", $utf8_csv));
$json = json_encode($array, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($status == 200){
echo "Post Successfully!";
}
}
我不熟悉 laravel,
但是你不需要添加行
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
之前
curl_exec($ch)?
你的错误在这一行
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
改成
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('json' => $json)));
让我知道进展如何!
情况
- 我想使用 php cURL post JSON 数据到我的 url
http://localhost/api_v2/url?key=***
这是我试过的
POST function
public function post(){
$ch = curl_init("http://localhost/api_v2/url?key=***");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$file_name = 'inventory.csv';
$file_path = 'C:\QuickBooks\'.$file_name;
$csv= file_get_contents($file_path);
$utf8_csv = utf8_encode($csv);
$array = array_map("str_getcsv", explode("\n", $utf8_csv));
$json = json_encode($array, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($status == 200){
echo "Post Successfully!";
}
}
我不熟悉 laravel,
但是你不需要添加行
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
之前
curl_exec($ch)?
你的错误在这一行
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
改成
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('json' => $json)));
让我知道进展如何!