Please, how to convert the following code to async GuzzleHttp?
In this way, php is waiting for the return of each query.
while ($p = pg_fetch_array($var)) {
$url = "https://url";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array("Content-Type: application/json");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{"s1":"s1","number":"'.$p['number'].'"}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
}
Here's a working example using native curl_multi_*() functions. Specifically:
curl_multi_init()
curl_multi_add_handle()
curl_multi_exec()
curl_multi_getcontent()
curl_multi_remove_handle()
curl_multi_close()
<?php
$urls = ['https://example.com/', 'https://google.com'];
$handles = [];
foreach ($urls as $url) {
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$handles[] = $handle;
}
$multiHandle = curl_multi_init();
foreach ($handles as $handle) {
curl_multi_add_handle($multiHandle, $handle);
}
for(;;){
curl_multi_exec($multiHandle, $stillRunning);
if($stillRunning > 0){
// some handles are still downloading, sleep-wait for data to arrive
curl_multi_select($multiHandle);
}else{
// all downloads completed
break;
}
}
foreach ($handles as $handle) {
$result = curl_multi_getcontent($handle);
var_dump($result);
curl_multi_remove_handle($multiHandle, $handle);
}
curl_multi_close($multiHandle);
Now, how convert the code cUrl to GuzzleHttp?
Related
I am wanting cURL to retry when cURL fails, but I have a situation like this
My function inside while loop is not working.
But when I remove the while loop, it works normally again.
Here is my function snippet:
function Curl($url){
$total_curl = 1;
$isRunning = true;
$sleep = 1;
while ($isRunning){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, $this->url ?? $url);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT,10);
$resp = curl_exec($curl);
if((!$resp || curl_errno($curl))){
if($total_curl > 3){
$isRunning = false;
}
sleep($sleep);
}
curl_close($curl);
$total_curl++;
}
return $resp;
}
The problem is in your while loop. If the curl is successful your while loop will run forever because the $total_curl variable is never checked in the nested if.
I would suggest using recursion for this, sicne i find it a bit cleaner and this is how i would approach it:
/**
* Solve using recursion cause it's fun
*/
function Curl($url, $times_run = 0)
{
// Condition that will break recursion, in this case if curl failed and run 3 times
if ($times_run > 3) {
return;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, $url); // replace this with $this->url ?? $url if you want but i removed it since i am not inside a class
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$resp = curl_exec($curl);
// Start recursive function if curl is not successful
if ((!$resp || curl_errno($curl))) {
Curl($url, $times_run++);
}
curl_close($curl);
return $resp;
}
The alternative would be to keep your way and just add a return $resp at the end of your while loop like so:
function Curl($url)
{
$total_curl = 1;
$isRunning = true;
while ($isRunning) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, $this->url ?? $url);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$resp = curl_exec($curl);
if ((!$resp || curl_errno($curl))) {
if ($total_curl > 3) {
$isRunning = false;
}
curl_close($curl);
$total_curl++;
} else {
curl_close($curl);
return $resp;
}
}
}
I hope this helps with your problem, cheers.
there is information received through CURL with the content:
login=Vasya Pupkin city=Moscow tel=0 123 456 567 sex=male
How do I properly break it into an array for further work with the data? At the moment I have this code, so why can not I skip it through foreach: Invalid argument supplied for foreach(). I understand this because the information received is not transferred to the array.
<?php
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Justice.ru");
$data = iconv('windows-1251', 'UTF-8', $data);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$lines = file_get_contents_curl('http://emeraldscity.combats.ru/inf.pl?short=1327641470');
foreach($lines as $value)
{
list($var, $val) = explode('=',$value);
$arr[$var] = $val;
}
echo $arr['login'];
?>
<?php
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Justice.ru");
$data = curl_exec($ch);
curl_close($ch);
$d = json_encode($data);
return json_decode($d , true);
}
$lines = file_get_contents_curl('http://emeraldscity.combats.ru/inf.pl?short=1327641470');
foreach($lines as $value)
{
list($var, $val) = explode('=',$value);
$arr[$var] = $val;
}
echo $arr[login];
?>
This tough must have a certain style like xml or json or array ..
With file_get_contents_curl you get a string, not an array. So before going through the lines you have to extract them from the string.
$content = file_get_contents_curl('http://emeraldscity.combats.ru/inf.pl?short=1327641470');
$lines = explode(PHP_EOL,$content);
foreach ($lines as $value) {
list($var, $val) = explode('=', $value);
$arr[$var] = $val;
}
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.
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.
i am using codeigniter and my code is as follows :
Controller :
$json_string = 'http://maps.googleapis.com/maps/api/directions/json?origin=' . $user_addr . '&destination=' . $vendor_city .'&mode=Montreal';
$json = $this->curl_get_contents($json_string);
$obj = json_decode($json, true);
$this->load->view('get_direction_pg',$obj);
public function curl_get_contents($url)
{
$ch = curl_init($url);
if ($ch == FALSE) {
return array('error' =>"failed");
}else{
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
$result = curl_exec($ch);
return $result;
}
}
and it if i access var_dump($routes);
it says,
undefined variable routes.
try using this: i.e. encoding the vars - before putting into url
$json_string = 'http://maps.googleapis.com/maps/api/directions/json?origin=' . urlencode($user_addr) . '&destination=' . urlencode($vendor_city) .'&mode=Montreal';
the parameters should be encoded for url, otherwise it is being invalid, and hence you are getting that error
Try this:
public function curl_get_contents($url)
{
$ch = curl_init($url);
if ($ch == FALSE) {
return array('error' =>"failed");
}
else
{
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
$result = curl_exec($ch);
return $result;
}
}
I have the following code which works;
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.nutritionix.com/v1_1/search");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"appId=id&appKey=key&query=milk");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
print_r($response);
?>
Question is, how do i specify fields to be outputted in the results?
I have tried, "appId=id&appKey=key&query=milk&fields=item_name, nf_calories" but to no avail..
Any help appreciated. Thanks.
Simply adding a question mark in between should do the trick really:
https://api.nutritionix.com/v1_1/search?appId=id&appKey=key&query=milk&fields=item_name
And so on for the field names.
I've generally used this approach when using curl, you can take a look at it if you want:
function curl_get_contents($url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
function getUrl()
{
$url = "https://api.nutritionix.com/v1_1/search?appId=id&appKey=key&query=milk&fields=item_name";
return $url;
}
function getData()
{
$i = 0;
$url = getUrl();
$response = curl_get_contents($url);
$data = json_decode($response);
if(!isset($data->data))
{
die("no data.");
}
$data = $data->data;
return $data;
}
EDIT: Try an url like this:
https://api.nutritionix.com/v1_1/search/milk?results=0:20&fields=item_name,brand_name,item_id,nf_calories&appId=APPID&appKey=APPKEY