【问题标题】:Convert a Curl Response String in JSON Array with PHP使用 PHP 转换 JSON 数组中的 Curl 响应字符串
【发布时间】:2018-11-03 12:20:04
【问题描述】:

我正在使用 Curl 从 REST API 获取请求。这是我的代码:

    #Curl init
    $ch = curl_init('https://192.168.0.1/api/invoke/LicenseRequest');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                'Content-Type: application/json',
                                                'Connection: Keep-Alive',
                                                'Accept: application/json'
                                                ));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

#Username und PW
    curl_setopt($ch, CURLOPT_USERPWD, "****:****");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

#Post
    $post = [];
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);

    curl_close($ch);

当我echo $response 出现时(gettype 返回字符串):

HTTP/1.1 200 OK Cache-Control: no-cache,private,no-store,must-revalidate,max-stale=0,post-check=0,pre-check=0 Pragma: no-cache Content-Length: 733 Content-Type: application/json Expires: Wed, 23 May 2018 09:53:48 GMT Server: Microsoft-***** Date: Thu, 24 May 2018 09:53:48 GMT { "error": null, "token": null, "statusVersion": 2, "statusCode": "succeeded", "percentProgress": null, "statusText": null, "result": { "productKey": "************", "productVersion": "10.2.3.12921", "timestamp": "2018-05-24T09:53:48.2029026Z", "machineName": "******", "configuredInstances": 3, "configuredInstanceHosts": 2, "configuredClientAccessServers": 1, "instanceData": [ { "id": "l_container1", "usedLicenseCount": 912 }, { "id": "l_container2", "usedLicenseCount": 7 }, { "id": "l_container3", "usedLicenseCount": 2 } ] }, "logOutput": null }

到目前为止,我认为很好。现在我想解析“instanceData”。我想我必须使用json_decode($response, true); 创建一个数组。 所以:

$result = json_decode($response, true);
echo $result;

但是当我打印每个回声时,该字段为空。 我没有收到错误消息,但该网站是空白的。

对不起我的英语,我希望你能帮助我。

【问题讨论】:

    标签: php arrays json curl


    【解决方案1】:

    如果您设置了CURLOPT_HEADERCURLOPT_RETURNTRANSFER,则返回的响应将在单个字符串中包含标头和正文。

    如果您只对正文感兴趣,请删除设置CURLOPT_HEADER 选项的行,您的响应将仅包含 JSON。然后,您可以使用json_decode(正如您已经尝试过的那样),并执行您需要的任何处理。

    如果您对标头感兴趣,则需要将它们与响应的其余部分分开:

    $response = curl_exec($ch);
    $info = curl_getinfo($ch);
    
    $response = [
      'headers' => substr($response, 0, $info["header_size"]),
      'body' => substr($response, $info["header_size"]),
    ];
    

    现在,$response['headers'] 将包含标头(作为字符串),$response['body'] 将包含 JSON。

    【讨论】:

    • 谢谢。我对标题不感兴趣。我删除了 CURLOPT_HEADER,现在响应显示为一个数组。
    猜你喜欢
    • 2020-11-17
    • 2016-09-26
    • 2016-07-01
    • 2022-12-18
    • 2016-12-09
    • 2022-11-19
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多