John Davidson

php - Multiple external scripts with output buffering

0 comments
Message:


Trying to create a batch job that calls 4 external php scripts. I can do this using curl_exec, but then it waits for all 4 scripts to complete before sending text to screen. I am sure this can be optimized, but can't really get it working.
Any suggestions on how to do this with curl_multi_getcontent + output buffering so it displays the data as it get's it from the external sites?



My Answer:
You can achieve this by using curl_multi_init to handle multiple curl requests simultaneously and output buffering to display the data as it is received from the external sites. Here's an example code snippet to demonstrate this:

php

// List of URLs to fetch data from
$urls = array(
'http://example.com/script1.php',
'http://example.com/script2.php',
'http://example.com/script3.php',
'http://example.com/script4.php'
);

// Initialize curl multi handler
$mh = curl_multi_init();

// Initialize array to store curl handles
$handles = array();

// Loop through each URL and create a curl handle for each
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}

// Execute all curl requests simultaneously
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);

// Loop through each curl handle to get the content and display it
foreach ($handles as $ch) {
$content = curl_multi_getcontent($ch);
echo $content;
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}

// Close curl multi handler
curl_multi_close($mh);

?>


This code will fetch data from each of the specified URLs simultaneously and display the content as it is received. You can modify the URLs in the $urls array to include your external scripts.

Rate this post

3 of 5 based on 3868 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us