I have used the code below with the Bing image API to search images. But the code gets only 50 results. How can I get more results?
$acctKey = 'Account key here';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = 'Kitchen';
$serviceOp = 'Image';
$market ='en-us';
$query = urlencode("'$query'");
$market = urlencode("'$market'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query&Market=$market";
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic $auth"
)
);
$context = stream_context_create($data);
$response = file_get_contents($requestUri, 0, $context);
$response=json_decode($response);
echo "<pre>";
print_r($response);
echo "</pre>";
You should append your request with $top=50&$skip=0 to get the first 50 results and with $top=50&$skip=51 to get the next 50 results, it's better to create API key to get the second request as Bing permits 1 transaction per second and you may get this message error if you exceeded the limits: "503 The number
of requests per minute for the subscription has reached the maximum threshold that is allowed."
Related
Let's say I have this code in PHP:
public function getFromAzure($searchParam, $jobCategory, $top, $skip, $request){
$listingManager = $this->get('rd.model_manager.job_listing');
$url = $listingManager->getAzureSearchParam($request, 'azure_search_idx');
$apiKey = $listingManager->getAzureSearchParam($request, 'azure_key');
$searchParam = preg_replace('/\s+/', '+', $searchParam);
$postdata = json_encode(
array(
'search' => $searchParam,
'filter' => $category,
'orderby'=> 'publishedDate desc',
'facets' => array('locationName','employmentType', 'workSchedule','jobFunction','positionLevel','industry'),
'top' => $top,
'skip' => $skip,
'count' => true
)
);
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Content-type: application/json\r\n" .
"api-key: ". $apiKey . "\r\n" .
"Accept: application/json",
'content'=>$postdata
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
$file = json_decode($file,true);
return $file;
}
Is there a way I can iterate the $skip inside this function(PHP)?
Currently I am iterating skip through Ajax call from javascript. 1 ajax call per (15 record) skip.
I need to iterate the skip because I need to load about 2,000 records(and counting)on page load, which per query is limited to 1,000. and assuming if I have 10,000 records or more. then I would have to run ajax every 1000 (for example) which could have performance issue.
btw fyi only- I need this on facets. where I have to iterate throught all records and get their value of my facet categories.
Thank you in advance! Cheers!
I work at an MSP and I'm trying to integrate our ticketing system (Autotask) with Slack. So far, I have set up an HTTP POST request to some PHP code when a new ticket is created, which posts a chat message in a certain channel ("New Ticket Created! [Ticket Title] - [Ticket Description]" etc.) using Incoming Webhooks. Below is the important bits of that code:
<?php
require_once __DIR__ . '/src/autoload.php';
//Gets ticket number from HTTP POST
$ticketNum = $_POST['subject'];
//Generated at api.slack.com/apps > Incoming webhooks (for the channel I'm posting in)
$responseURL = 'https://hooks.slack.com/services/XXXXXXXXXXXX';
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
//*****
//QUERYING TICKETING SYSTEM API FOR TICKET INFORMATION
//THIS CODE WORKS, OMITTED FOR EASIER READING
//*****
$r = new Response();
$r->response_type = "in_channel";
$r->text = "New Ticket Created: \n*".$ticketName."* (".$ticketNum.") \n".$ticketDescription;
$r->attachments = array(
0 => array('callback_id' => 'newTicketAction', 'text' => 'Select an action:',
'color' => '95baa9', 'actions' => array(
0 => array('name' => 'newTicketAction', 'text' => 'Accept', 'type' => 'button',
'value' => 'accept', 'style' => 'primary'),
1 => array('name' => 'newTicketAction', 'text' => 'View', 'type' => 'button',
'value' => 'view')
)
)
);
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
This works and posts a message in the correct channel that looks like this:
The problem I'm having is with responding to those button clicks. I have my Request URL set up, pointing to another PHP script. My understanding is that the button click sends another HTTP POST request to this page with a JSON object, which has a payload item. My hunch is I'm accessing this incorrectly. My code is below:
<?php
require_once __DIR__ . '/src/autoload.php';
//get information from HTTP POST, sent at button click
$payload = $_POST['payload'];
$data = json_decode($payload,true);
$responseURL = $data -> response_url;
class Response {
public $response_type = "";
public $text = "";
public $attachments = array();
}
$r = new Response();
$r->response_type = "in_channel";
$r->text = "Ticket Accepted";
header('Content-Type: application/json');
//Using CURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $responseURL,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($r)
));
$resp = curl_exec($curl);
var_dump($resp);
curl_close($curl);
?>
You can see right now I'm just trying a simple response message for testing purposes, but when I click the 'Accept' button I get the following response:
I've scoured the web and cannot find a solid tutorial on Interactive Messages which includes "receiving" button clicks. Any help would be greatly appreciated.
PHP syntax was wrong for accessing array element.
I am trying to get search results as per the api documentation
Here is what I wrote in PHP
require_once 'HTTP/Request2.php';
$api_key = 'my_bing_search_api_key';
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
$headers = [
'Ocp-Apim-Subscription-Key' => $api_key
];
$request->setHeader($headers);
$url = $request->getUrl();
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
$url->setQueryVariables($parameters);
$request->setMethod(\HTTP_Request2::METHOD_GET);
$request->setBody("{body}");
$search_result = null;
try {
$response = $request->send();
$search_results = json_decode($response->getBody(), true);
return $search_results;
} catch (HttpException $ex) {
return [];
}
I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only.
I tested the same request in the api console. There I am getting the webPages property in the json response.
Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?
From the code snippet, you are passing the keyword to Bing web search API after encoding it.
$url_encoded_keyword = urlencode('animation concepts and tutorials');
$parameters = [
'q' => $url_encoded_keyword,
'count' => '10',
'offset' => '0',
'safesearch' => 'Strict',
);
Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as
https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation
concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate
I have a php script to update my subscribers from my wordpress userlist to Mailchimp using batch-subscribe. (https://apidocs.mailchimp.com/api/2.0/lists/batch-subscribe.php)
Everything works fine when I submit about 400 records. All records are added, and I get a return from the API with the number of added records, etc.
If I submit about 600 or more (I have about 730 subscribers), all records are added to Mailchimp, but the API returns FALSE. I double checked it with === false, and it is false. I get no errors -- it just returns false (but all records are added to Mailchimp).
Mailchimp says "Maximum batch sizes vary based on the amount of data in each record, though you should cap them at 5k - 10k records, depending on your experience." (https://apidocs.mailchimp.com/api/2.0/lists/batch-subscribe.php).
I'm nowhere close to that, and every record is being added to the mailchimp list just fine. I just don't get the return from the API.
I've increased my timeout value to 5 minutes. I also switched to using different records, suspecting I might have had a record with something that was causing it to mess up, but it had the same behavior with different records.
I'm using the DrewM library to interface with Mailchimp API version 2.0. I double checked to make sure DrewM is using post for the request, and it does. (https://github.com/drewm/mailchimp-api/)
Any ideas what is causing this?
Here is the code:
function mailchimpdailyupdate () {
set_time_limit(300);
$api = get_mc_api();
$mcListId = get_mc_mailing_list();
$MailChimp = new \Drewm\MailChimp($api);
...
foreach ( $blogusers as $user ) {
$userinfo = get_userdata( $user->ID );
$location = ...//code to get location
$merge_vars = array(
'FNAME'=> $userinfo->first_name,
'LNAME'=> $userinfo->last_name,
'MMERGE3'=> $userinfo->user_login, //username
'MMERGE6'=> $location //location
);
$batch[] = array(
'email' => array('email' => $user->user_email),
'merge_vars' => $merge_vars
);
} //end foreach
//mailchimp call
$retval = $MailChimp->call('lists/batch-subscribe', array(
'id' => $mcListId, // your mailchimp list id here
'batch' => $batch,
'update_existing' => true
)
);
if ($retval === false) {
echo "Mailchimp API returned false";
}
echo 'Added: ' . $retval['add_count'] . "<br/>";
echo 'Updated: ' . $retval['update_count'] . "<br/>";
echo 'Errors: ' . $retval['error_count'] . "<br/>";
}
With help from Mailchimp support, I was able to locate and solve the problem.
The issue was actually in the DrewM wrapper.
The content-length section of the header was apparently not working correctly on long calls. I removed it, and everything began working fine.
Original section of DrewM code (not working):
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'protocol_version' => 1.1,
'user_agent' => 'PHP-MCAPI/2.0',
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'content' => $json_data,
),
)));
Updated section of code (working):
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'protocol_version' => 1.1,
'user_agent' => 'PHP-MCAPI/2.0',
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n",
'content' => $json_data,
),
)));
Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)