简体   繁体   中英

PHP get_file_contents asynchronously

我只是想知道是否有人设法异步获取远程URL的内容,处理它然后输出到当前文档而不使用AJAX。

PHP is single threaded. You have to use browser capabilities to fork another process.

Javascript can be asynchronously and you need it for your case.

Not with file_get_contents, no. Alternatively you can use the CURL extension and their non-blocking IO capabilities. All of this is available via the Multi Handlers of CURL. It's 'async' in the sense that you may poll the result and continue processing on other things if the result isn't ready to be read. This makes it 'async' in the sense that you're never blocking and waiting for the response, as long as there's work to be done - do it.. What's hard to understand for some people is the difference between async and non-blocking, in most cases with PHP what you really want is some sort of NB I/O. Given a few abstraction layers you can really come up with a nice IO callback interface with all the fun of anon functions, but thats another story..

See http://www.php.net/manual/en/function.curl-multi-init.php this is where it starts, the example included is great See http://www.php.net/manual/en/function.curl-multi-exec.php See http://www.php.net/manual/en/function.curl-multi-select.php for the NB poller

This guy avoids the ease of curl and goes straight to handling the http protocol which is yet another solution https://segment.io/blog/how-to-make-async-requests-in-php/ but requires a bit more of knowledge of the socket api.

Cheers

What you can do is create non blocking socket connections in PHP, which means your code can work on something else (eg print out HTML + flush() to the Browser) while the data from your connection is loading, then poll it later.

Just google for 'php asynchronous sockets'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM