首页 > 解决方案 > 如何访问 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);

请帮我吃!!我有麻烦也很着急!!

标签: phpjsoncodeignitercurlhttps

解决方案


如果响应如下:

[{"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);;
    }
?>

推荐阅读