How to Receive Data Output Using echo in a Loop in an API in php

Asked 1 years ago, Updated 1 years ago, 449 views

In laravel, I created an API that outputs JSON search results, but since there is a lot of data to output, I created it to send data in split echo.In this case, if I want to run the API within php of another environment and receive all the data and process it, how should I receive it?
(You can retrieve it successfully by running it in your browser)

PHP returns NULL when you do the following:

$http=new\GuzzleHttp\Client([~]);
$response=$http->post('URL'~~~
var_dump(json_decode(string)$response->getBody(), true));
exit;

[Additional note]
·The first time data sent by echo from API

[
{data:[~]},

·Second time

 {data:[~]},

·Third time

{code:200,message:~}
]

·If you combine the first to third times, it will be json data.

[
{data:[~]},
{data:[~]},
{code:200, message:~}
]

php laravel

2022-12-07 16:30

2 Answers

The direction of the idea of dividing data itself is not bad, but if you want to divide it, you will need information on what part of the data you want to exchange after the second communication.

For example, if you have a total of 1,000 pieces of data, divide them into 50 pieces and the API will return the data.

  • First time: Return 1st to 50th cases as "offset 0"
  • Second time: 51st to 100th time return as offset 1

Also, I think it would be better to divide the unit of division by record while maintaining the data as JSON, rather than mechanically dividing it by the number of lines.

"If you search the web using ""apipagination"" in this area, you will find useful information."


2022-12-07 23:14

The API seems to be responding by streaming.

Therefore, the recipient must also receive and parse the response by streaming.

There was a similar question in the English version.

PHP HTTP Guzzle client-How to parse a JSON Array using Guzzle Streams-Stack Overflow

Why don't you use the JsonCollectionParser introduced here and give $response->getBody() as the streaming source and use the parser function to handle it properly?

$parser->parse($response->getBody(), function(array$item){
    var_dump($item);
});


2022-12-07 23:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.