从 header cURL php 检索响应代码

Retrieve the response code from header cURL php

我正在尝试使用 cURL PHP.

从响应 header 中获取响应代码

当我发送请求时,这是 MYOB AccountRight API:

返回的响应 header
HTTP/1.1 200 OK
Access-Control-Expose-Headers: Request-Context
Cache-Control: must-revalidate, private
Content-Encoding: gzip
Content-Type: application/json;charset=utf-8
Date: Thu, 20 May 2021 01:07:56 GMT
ETag: "XXXXXXXXX"
Expires: -1
Request-Context: appId=cid-v1:a4936349-ef26-4f8a-9268-XXXXXXXXX
Server: Microsoft-IIS/10.0
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Mashery-Message-ID: 2fc6b494-54e8-43e2-8bc4-XXXXXXXXX
X-Mashery-Responder: prod-j-worker-ap-southeast-2b-33.mashery.com
x-myobapi-elapsed: 1370
x-myobapi-requestid: bb0764c8-f62d-4848-bcae-XXXXXXXXX
X-Powered-By: ASP.NET
Content-Length: 1205
Connection: keep-alive

我试过 的解决方案,但我不会获取 http 代码。

这是我获取帐户数据的代码:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://ar1.api.myob.com/accountright/766d620e-a5eb-41c3-8343-XXXXXXXX/GeneralLedger/Account?$filter=Name%20eq%20\'Inventory\'%20or%20Name%20eq%20\'Cost%20Of%20Sales\'%20or%20Name%20eq%20\'Inventory%20Income\'',
  CURLOPT_HEADER => true,
  CURLOPT_NOBODY => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'x-myobapi-version: v2',
    'Accept-Encoding: gzip,deflate',
    'x-myobapi-key: '.$theAPIKey,
    'x-myobapi-cftoken: '.$theCFToken,
    'Authorization: Bearer '.$theAccessToken
  )
));

$response = curl_exec($curl);
$theInfo = curl_getinfo($response);
$http_code = $theInfo['http_code'];
curl_close($curl);
echo 'http code: ' . $http_code . '<br />';
echo '<pre>';
echo $response;
echo '</pre>';

当我回显 http 代码时,不会打印任何内容。

我认为您需要将 $curl 传递给 curl_getinfo 方法,而不是 $response

$response = curl_exec($curl);
$theInfo = curl_getinfo($curl);
$http_code = $theInfo['http_code'];

你可以在这里看到 doco.. https://www.php.net/manual/en/function.curl-getinfo.php