【问题标题】:Assign getBody() to a Variable Guzzle将 getBody() 分配给变量 Guzzle
【发布时间】:2020-10-07 14:38:41
【问题描述】:

我正在使用 Guzzle 发出 Http 请求, 我得到了预期的回复,但我想根据收到的回复做出一些决定,但我没有得到任何帮助。

到目前为止我所尝试的 我尝试将响应分配给变量

  $result= $response->getBody(); // {"id": 1420053, "name": "guzzle", ...}
  echo $result; //{"id": 1420053, "name": "guzzle", ...}
  $someArray = json_decode($result);
  echo $someArray;  //<!-- Object of class stdClass could not be converted to string (500 Internal Server Error) -->

echo '<pre>' . print_r($response->getBody()->getContents(), true) . '</pre>'; //<pre></pre>

echo '<pre>' . print_r($response->getBody()) . '</pre>'; /***
GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private
] => Resource id #495
    [size:GuzzleHttp\Psr7\Stream:private
] => 
    [seekable:GuzzleHttp\Psr7\Stream:private
] => 1
    [readable:GuzzleHttp\Psr7\Stream:private
] => 1
    [writable:GuzzleHttp\Psr7\Stream:private
] => 1
    [uri:GuzzleHttp\Psr7\Stream:private
] => php: //temp [customMetadata:GuzzleHttp\Psr7\Stream:private
] => Array
        (
        )

)
<pre>1</pre>
**/


return response()->json(["body"=>$result],201); //{"body": {},}

我将非常感谢任何帮助

$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}```

【问题讨论】:

    标签: php laravel lumen guzzle


    【解决方案1】:

    响应是一个流,转换它:

    $contents = (string)$response->getBody();
    

    【讨论】:

      【解决方案2】:

      如果你想要一个数组添加所需的标志,json_encode 默认返回一个 stdClass 对象

      $someArray = json_decode($result,true);
        print_r($someArray);
      

      此外,如果您使用 json 响应,您也可以这样做

      $result= $response->json()
      

      【讨论】:

        猜你喜欢
        • 2014-05-11
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多