I have this code
I need a loop to be able to print all results which are 400-600 but I'm not able because I'm limited to only 100 shows per page and I need a loop/while to make the same request but changing the page and then print the result and I'm not able to make it, can someone explain me how to implement here a loop or to give me some examples?
<?php
include('config/config.php');
$ch = curl_init();
$username = '**************';
$password = ''**************';';
$hash = base64_encode($username . ':' . $password);
$headers = array(
'Authorization: Basic ' . $hash
);
$query = $connection->query("SELECT id_xyz_ro as prods FROM stock_prods where id_xyz_ro > 0");
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['prods'];
}
$connection->query('SET session group_concat_max_len=15000');
foreach($connection->query("SELECT GROUP_CONCAT(CONCAT('\'', id_xyz_ro, '\'')) as prods FROM stock_prods where id_xyz_ro > 0") as $row) {
}
$datas = array(
'id' => $array,
'itemsPerPage' => '100', //Only 100 because API it's limiting me at 100 shows per page
'currentPage' => '1' //Here I need to loop
);
$data = array(
'data' => $datas
);
set_time_limit(0);
$url = "www.xyz.net/api-3/product_offer/read";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
print_r($result); //After loop I need to print results from all loops
?>
Thanks in advance
Related
I've wanted to scrape some useful data from a site. But the request only returned 25 results
with this:
$url = 'https://api.test.org';
$ch = curl_init();
$jsonData = array(
'limit' => 100, //user inputs pages * 5
'listType' => 'taskSolutions',
'task' => $taskid //taken from input user substr($_POST['link'],28);
//'skip' => 25 $variable that increases by 25
);
curl_setopt($ch, CURLOPT_URL, $url);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); // loop adding 25 each time to skip
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch),true);
Now I looked at the website and they have the parameter 'skip' to get more results.
But now for the question:
How could I make a loop that adds 25 to the skip $variable and resends the CURLOPT_POSTFIELDS and add that data to $data
A variable $totalcount is available to check howmuch records there are.
You can do this with a loop. For instance, put the code above in a function called getData and pass it two arguments, $skip and $taskId :
function getData($skip, $taskid)
{
$url = 'https://api.test.org';
$ch = curl_init();
$jsonData = array(
'limit' => 100, //user inputs pages * 5
'listType' => 'taskSolutions',
'task' => $taskid //taken from input user substr($_POST['link'],28);
'skip' => $skip
);
curl_setopt($ch, CURLOPT_URL, $url);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); // loop adding 25 each time to skip
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return json_decode(curl_exec($ch),true);
}
You can then write a loop to increment the $skip variable by 25 until it reaches $totalCount. In each iteration, add the returned elements to the $data array :
$data = [];
for($skip = 0; $skip < $totalCount; $skip += 25)
{
foreach(getData($skip, $taskid) as $entry)
{
$data[] = $entry;
}
}
I'm using the Aliexpress API generatePromotionLinks. This API requires an parameter which is _aop_signature
URL is this :
https://gw.api.alibaba.com/openapi/param2/1/portals.open/api.generatePromotionLinks/[appKey]?trackingId=[trackingId]&targetUrls=[url]&locale=[global]&linkType=HOT_PRODUCT_LINK&_aop_signature=[signature]
I want to know where I can get the _aop_signature, or how to generate the _aop_signature using PHP.
<?php
$url = 'https://gw.api.alibaba.com/openapi/';
$appKey = ***;
$appSecret ='***';
$apiInfo = 'param2/1/portals.open/api.generatePromotionLinks/' . $appKey;
$code_arr = array(
'urls' => 'https://ru.aliexpress.com/af/mp3.html?d=y&origin=n&SearchText=mp3&catId=0&initiative_id=SB_20191106040548',
'linkType' => 'SEARCH_LINK',
'fields' => 'promotionUrls,trackingId,publisherId',
'trackingId' => 'Please create a unique affiliate ID for your site(s).',
);
$aliParams = array();
foreach ($code_arr as $key => $val) {
$aliParams[] = $key . $val;
}
sort($aliParams);
$sign_str = join('', $aliParams);
$sign_str = $apiInfo . $sign_str;
$code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
$url = $url.$apiInfo.'?'.http_build_query($code_arr)."&_aop_signature=".$code_sign;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
print_r($response);
?>
My for loop can run twice, but it only run once when I use the cURL in for loop
My for loop can run twice, but it only run once when I use the cURL in for loop
public function index_onSync () {
$checkedIds = post('checked');
$data = ModelsAdmin::select('id', 'address', 'private_key')->whereIn('id', $checkedIds)->get();
$sync_data = array();
for ($i=0; $i < count($data); $i++) {
$url_confirm = "http://127.0.0.1:50233/sync";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_confirm);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
$post_data = array( "id"=>$data[$i]['id'], "address"=>$data[$i]['address'], "private_key"=>$data[$i]['private_key'] );
$json_data = json_encode($post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: '.strlen($json_data)
));
curl_setopt($ch, CURLOPT_POSTFIELDS,$json_data);
$data = curl_exec($ch);
$data = json_decode($data);
array_push($sync_data, $data);
echo $data;
curl_close($ch);
}
var_dump($sync_data);
}
You're overriding your $data array from ModelsAdmin::select in line
$data = curl_exec($ch);
So, on the second iteration, your data is not a 2-rows array anymore...
Instead of $data, you could use $response, for example...
I wanted to make an inline bot! and when i do this:
function sendResponse($url, $data){
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('inline_query_id' => $data['inline_query_id'], 'results' => json_encode($data['results'])));
$output = curl_exec($ch);
return $output;
}
It wont work, the error (with or without the header): {"ok":false,"error_code":400,"description":"[Error]: Bad request: Field \"message_text\" must be of type String"}
but when I do it like this:
function sendResponse($url, $data){
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_URL, $url.'?inline_query_id='.rawurlencode($data['inline_query_id']).'&results='.rawurlencode(json_encode($data['results'])));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $q);
$output = curl_exec($ch);
return $output;
}
It works ! the problem is the second method request URI will be too large so I cannot use it!
Any way I can send these data is okay with me! thanks!
and the code for making $data is here:
$result = connectWebsite(SITE_SEARCH_URL, urlencode($update['inline_query']['query']));
$result = json_decode($result);
$output = array();
$output['inline_query_id'] = $update['inline_query']['id'];
$i = 0;
foreach($result as $post){
$data = array();
$data['type'] = 'article';
$data['id'] = strval($post->ID);
$data['title'] = '('.$post->atypes.') '.$post->title;
if(strlen($post->content) > 2100)
$tmp = substr($post->content, 0, 2096).'...';
$data['message_text'] = '<b>'.$post->title.'</b>'.ucwords($post->genre, ',').$tmp;
$data['parse_mode'] = 'HTML';
if(strlen($post->content) > 200)
$tmp = substr($post->content, 0, 196).'...';
//$data['description'] = ucwords($post->genre, ',').' | '.$tmp;
$output['results'][$i] = $data;
$i++;
if($i == MAX_RESULTS)
break;
}
sendResponse(API_URL.'answerInlineQuery', $output);
It might help someone so I'll answer it myself.
the problem was the UTF-8 encoding
I replaced substr with mb_substr
besides at the first line I'v added this: mb_internal_encoding("UTF-8")
and ... the problem was solved. now I can send my inline query results (or any other command) without the URL length problem
Thanks everyone for your help
I want to pass value from API to array but I am not able to figureout what code I need to write. currently it returns [1481367,7546218] how can I pass this in array
$content = array($result) ;
Below is the API Code
$Login = 8632465; #Must be Changed
$apiPassword = "Kcfve123*"; #Must be Changed
$data = array("Login" => $Login, "Password" => $apiPassword);
$data_string = json_encode($data);
$ch = curl_init('http://client-api.instaforex.com/api/Authentication/RequestPartnerApiToken');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
$token = curl_exec($ch);
curl_close($ch);
$apiMethodUrl = 'partner/GetReferralAccounts/'; #possibly Must be Changed
$parameters = $Login; #possibly Must be Changed. Depends on the method param
$ch = curl_init('http://client-api.instaforex.com/'.$apiMethodUrl.$parameters);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); # Turn it ON to get result to the variable
curl_setopt($ch, CURLOPT_HTTPHEADER, array('passkey: '.$token));
$result = curl_exec($ch);
//$result = trim(preg_replace('[]','',curl_exec($ch)));
curl_close($ch);
If the CURL result is "[1481367,7546218]", then to convert this into an array:
`$content = json_decode($result,TRUE); //Here $result = "[1481367,7546218]"`
Printing the variable $content using var_dump() variable will output:
array(2) {
[0] => int(1481367)
[1] => int(7546218)
}