php - 如何访问 CURL 以从 php 获取 json 数据
问题描述
如何访问 CURL 以从 php.ini 获取 json 数据。顺便说一句,我正在使用 codeigniter 框架。
这是卷曲数据:
curl -u <YOUR_KEY_ID>:<YOUR_SECRET> \
-X POST https://api.razorpay.com/v1/orders \
-H "content-type: application/json" \
-d '{
"amount": 50000,
"currency": "INR",
"receipt": "receipt#1"
}'
这是我可能的工作:
$url = 'https://api.razorpay.com/v1/orders';
$curl = curl_init($url);
$data = json_encode(array(
'receipt'=> $orderId,
'amount'=>$amount,
'currency'=> 'INR'
), JSON_FORCE_OBJECT);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json'
//$keyId.':'.$secretKey
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
请帮我吃!!我有麻烦也很着急!!
解决方案
如果响应如下:
[{"data1":"value1","data1.1":"value1.1"},{"data2":"value2","data2.1":"value2.1"}...]
利用 :
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$json = file_get_contents('thelink', false, stream_context_create($arrContextOptions));
$result = json_decode($json, true);
并称之为:
echo $result[0]["data1"];
echo $result[0]["data1.1"];
echo $result[0]["data2"];
echo $result[0]["data2.1"];
如果您仍想使用 curl(weatherAPI 上的示例):
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=1",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-rapidapi-host: weatherapi-com.p.rapidapi.com",
"x-rapidapi-key: aaaaxxxxbbbb"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$weather = json_decode($response);;
}
?>
推荐阅读
- python-3.x - 自定义损失函数不能与阈值微分
- laravel - Laravel Passport 不返回不记名令牌
- haskell - Haskell IO 缩进
- php - 如何在 php 中使用 pdo 连接调用 SQL Server 存储过程?
- liferay - Liferay 6.2 到 7.1.1 的迁移
- docker - Docker-Compose 入口点/命令
- java - 使用 for 循环的 Java 阶乘代码未显示准确的输出
- r - 为什么切片函数在不明确使用 dplyr 的情况下不起作用
- sql-server - SQL Server 转到光标所在的下一行
- css - ReactJS:标签无法从远程 url 加载图像并转换提供的 url 失败并出现 404