从curl结果获取值

时间:2019-03-30 20:11:50

标签: php curl

我正在尝试从结果中获取ID。如何只打印ID?

我尝试过decode $resp,但似乎是array的问题。

    //API Url
    $url = 'https://api.clover.com:443/v3/merchants/'.$merchantid.'/orders/';

    //Initiate cURL.
    $ch = curl_init($url);

    //The JSON data.
    $jsonData = array(
        'state' => 'open',
        'title' => '0010-W'
    );

    $headers = array(
        'Content-type: application/json',
        'Authorization: Bearer '.$authtoken.' ',
    );
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);

    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //<=====This was missing.

    curl_setopt($ch, CURLOPT_HEADER, false);

    $resp = curl_exec($ch);


    $data = json_decode($resp, true);
    echo 'ID: '.$data['id'];
{
"href": "https://www.clover.com/v3/merchants/***/orders/D4MHB7M5D0P86", 
"id": "D4MHB7M5D0P86", 
"currency": "USD", 
"title": "0010-W", 
"taxRemoved": false, 
"isVat": false, 
"state": "open", 
"manualTransaction": false, 
"groupLineItems": true, 
"testMode": false, 
"createdTime": 1553976014000, 
"clientCreatedTime": 1553976014000, 
"modifiedTime": 1553976014000
}

我希望获得ID,但结果为空。


重复出现的问题是在解释不同的内容而不是cURL数据。

已解决-用答案编辑了问题。 CURLOPT_RETURNTRANSFER需要设置才能打印数据。经过测试并完美运行。

0 个答案:

没有答案