Is making asynchronous HTTP requests possible with PHP?

前端 未结 5 1399
情歌与酒
情歌与酒 2020-11-27 17:42

I have a PHP script that needs to download several files from a remote server. At the moment I just have a loop downloading and processing the files with cURL, which means t

5条回答
  •  长情又很酷
    2020-11-27 18:38

    For PHP5.5+, mpyw/co is the ultimate solution. It works as if it is tj/co in JavaScript.

    Example

    Assume that you want to download specified multiple GitHub users' avatars. The following steps are required for each user.

    1. Get content of http://github.com/mpyw (GET HTML)
    2. Find and request it (GET IMAGE)

    ---: Waiting my response
    ...: Waiting other response in parallel flows

    Many famous curl_multi based scripts already provide us the following flows.

            /-----------GET HTML\  /--GET IMAGE.........\
           /                     \/                      \ 
    [Start] GET HTML..............----------------GET IMAGE [Finish]
           \                     /\                      /
            \-----GET HTML....../  \-----GET IMAGE....../
    

    However, this is not efficient enough. Do you want to reduce worthless waiting times ...?

            /-----------GET HTML--GET IMAGE\
           /                                \            
    [Start] GET HTML----------------GET IMAGE [Finish]
           \                                /
            \-----GET HTML-----GET IMAGE.../
    

    Yes, it's very easy with mpyw/co. For more details, visit the repository page.

提交回复
热议问题