PHP:在Laravel中解析Web API响应

时间:2018-11-30 09:06:05

标签: php laravel guzzle guzzle6

我必须在Laravel中使用旧的Web API。

响应正文如下:

TRANSACTION_ID: KJASDFYDSF^SDFHJSD/2236
STATUS: OK
DATE: 01/03/18

如何使用Guzzle 6将响应转换为Array?

1 个答案:

答案 0 :(得分:2)

这是解析响应的解决方案:

private function parseResponse(\GuzzleHttp\Psr7\Response $response) {
    $body = $response->getBody();
    $body->rewind();
    $content = (string) $body->getContents();
    $lines = explode(PHP_EOL, $content);
    $result = [];

    foreach ($lines as $line) {
        $chunks = explode(':', $line);
        $result[trim($chunks[0])] = trim($chunks[1]);
    }

    return $result;
}