phparrayscurlcurl-multi

Adding values to array from multiple curl requests


I am currently using php-curl-class and I am trying to create an array of urls from JSON responses that match the error code in my code below. My latest try was using array_push which resulted in the urls creating an array of the same urls like this.

Array
(
    [0] => http://example.com
    [1] => http://example.com
)

And what I am trying to achieve is something like this.

Array
(
    [0] => http://example.com
    [1] => http://example2.com
    [2] => http://example3.com
    [3] => http://example4.com

)

My code:

require __DIR__ . '/vendor/autoload.php';
use \Curl\MultiCurl;

$curl_opts = [
    CURLOPT_VERBOSE=> true
];

$out = array();
$errors = array();
$multi_curl = new MultiCurl();

$multi_curl->success(function ($instance) use (&$con, $out, $errors) {
    $out[$instance->out] = $instance->response;

   foreach ($out as $output){
        $error = $output->error;
        $p_id = $output->p_id;

    if (isset($error) && $error == '2'){
        echo '2 error';
        $errors[] = $instance->url;
        array_push($errors, $instance->url);
    }
}
    print_r($errors);
});

foreach($curl_opts as $key=>$value)
    $multi_curl->setOpt($key, $value);

$multi_curl->complete(function($instance){
    echo 1;
});

$multi_curl->addGet('http://example.com');
$multi_curl->addGet('http://example2.com');
$multi_curl->addGet('http://example3.com');
$multi_curl->addGet('http://example4.com');

$multi_curl->setConcurrency(3);
$multi_curl->start();

var_dump($multi_curl);

Anyone have any suggestions? Thanks.


Solution

  • I figured it out. I have had the same issue in the past using RollingCurl. I forgot to add & at the beginning of the arrays in the success function.
    Instead of this:

    $multi_curl->success(function ($instance) use (&$con, $out, $errors) 
    

    It should have been this:

    $multi_curl->success(function ($instance) use (&$con, &$out, &$errors) 
    

    If you want to access values outside of the loop you must define & before your variable like I just showed. I do not know of another way, if someone knows something better I'd be happy to hear it.