1

I want to access multiples urls via curl and print the son output. I've seen this: multiple cURL and output JSON? but I`am not able make it work anyway...

my code:

<?php
$urls = Array(
 'URLtoJSON1',
 'URLtoJSON1'
);

for($i = 0; $i < 3; $i++) {
  $curl[$i] = curl_init($urls);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($curl, CURLOPT_USERPWD, "YYY:XXX");
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
  $curl_response[$i] = curl_exec($curl);
  curl_close($curl);

  $data = json_decode($curl_response[$i]);
  $name[$i] = $data->fullDisplayName;
  $datum[$i] = $data->timestamp;
  $result[$i] = $data->result;

}

// here I`d love to be able echo output $name[URLtoJSON], etc...
?>

thank you for any help.

1 Answer 1

1

Instead of doing a for loop, you can make a foreach loop that iterates over your $urls array by doing foreach ($urls as $key=>$url). $key will hold the index of the array (starting at 0) and $url will hold the URL.

Here is what the resulting code would look like:

$urls = Array(
    'URLtoJSON1',
    'URLtoJSON2'
);

foreach ($urls as $key=>$url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "YYY:XXX");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $ch_post_data);
    $ch_response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($ch_response);
    $name[$key] = $data->fullDisplayName;
    $datum[$key] = $data->timestamp;
    $result[$key] = $data->result;
}

Now if you want to access $name of the first URL, you would just do $echo $name[0];

You can also access $datum or $result in a similar way.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Working like a charm :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.