0

I have to consume an old Web API in Laravel.

Response body looks like this:

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

How can I convert the response into Array using Guzzle 6?

4
  • 4
    Why would you parse it into JSON? Commented Nov 30, 2018 at 9:07
  • 2
    Don't convert the response into JSON, just parse the response in that format. Converting to JSON would anyway require you to parse the response first, so why add the extra - useless - step? Commented Nov 30, 2018 at 9:08
  • I need to get the TRANSACTION_ID, STATUS and other properties from the response. Is it possible to do this automatically with Guzzle or I need to parse them with Regex? Commented Nov 30, 2018 at 9:19
  • 1
    you have to parse them manually. The given format is not a standard. Usually its being sent as JSON/xml/querystring but this you'll have to parse manually Commented Nov 30, 2018 at 9:28

1 Answer 1

2

Here is the solution with parsing response:

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also it's better to call explode() with the third, $limit parameter: $chunks = explode(':', $line, 2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.