Bing search API and Azure - php

I am trying to programatically perform a search on Microsoft Bing search engine.
Here is my understanding:
There was a Bing Search API 2.0 , which will be replaced soon (1st Aug 2012)
The new API is known as Windows Azure Marketplace.
You use different URL for the two.
In the old API (Bing Search API 2.0), you specify a key (Application ID) in the URL, and such key will be used to authenticate the request. As long as you have the key as a parameter in the URL, you can obtain the results.
In the new API (Windows Azure Marketplace), you do NOT include the key (Account Key) in the URL. Instead, you put in a query URL, then the server will ask for your credentials. When using a browser, there will be a pop-up asking for a/c name and password. Instruction was to leave the account name blank and insert your key in the password field.
Okay, I have done all that and I can see a JSON-formatted results of my search on my browser page.
How do I do this programmatically in PHP? I tried searching for the documentation and sample code from Microsoft MSDN library, but I was either searching in the wrong place, or there are extremely limited resources in there.
Would anyone be able to tell me how do you do the "enter the key in the password field in the pop-up" part in PHP please?
Thanks alot in advance.

Documentation for new services can get a bit interesting - especially in the rabbit-warren of MSDN. The most clear explanation I can find is on the Migration Guide from this Bing Search API page. Best of all the migration guide has a nice simple example in PHP towards the end.
EDIT: Alright, the migration guide is a starting point, but it isn't the best example. Here are two methods that work for me (no proxy, firewalls etc. interfering):
Using file_get_contents
Note: 'allow_url_fopen' needs to be enabled for this to work. You can use ini_set (or change php.ini etc.) if it isn't.
if (isset($_POST['submit']))
{
// Replace this value with your account key
$accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Web?$format=json&Query=';
$cred = sprintf('Authorization: Basic %s',
base64_encode($accountKey . ":" . $accountKey) );
$context = stream_context_create(array(
'http' => array(
'header' => $cred
)
));
$request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');
$response = file_get_contents($request, 0, $context);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
echo('<li class="resultlistitem"><a href="'
. $value->URL . '">'.$value->Title.'</a>');
}
echo("</ul>");
}
Using cURL
If cURL is installed, which is normal these days:
<?php
$query = $_POST['searchText'];
$accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
$serviceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$webSearchURL = $serviceRootURL . 'Web?$format=json&Query=';
$request = $webSearchURL . "%27" . urlencode( "$query" ) . "%27";
$process = curl_init($request);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "$accountKey:$accountKey");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($process);
$response = json_decode($response);
echo "<ol>";
foreach( $response->d->results as $result ) {
$url = $result->Url;
$title = $result->Title;
echo "<li><a href='$url'>$title</a></li>";
}
echo "</ol>";
?>
[WTS] changed SearchWeb to Search.

None of the above worked for me. Im running MAMP, this may be relevant. Try the below:
$accountKey = '=';
function sitesearch ($query, $site, $accountKey, $count=NULL){
// code from http://go.microsoft.com/fwlink/?LinkID=248077
$context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$ServiceRootURL = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&';
$WebSearchURL = $ServiceRootURL . '$format=json&Query=';
$request = $WebSearchURL . urlencode("'$query'"); // note the extra single quotes
if ($count) $request .= "&\$top=$count"; // note the dollar sign before $top--it's not a variable!
return json_decode(file_get_contents($request, 0, $context), true);
}
$q = "query";
if ($q){
// get search results
$articles = sitesearch ($q, $_SERVER['HTTP_HOST'], $accountKey , 100);
foreach($articles['d']['results'] as $article) {
echo " <p>".$article['Title'].'</p>';
echo " <p>".$article['Description'].'</p>';
echo " <p>".$article['Source'].'</p>';
echo " <p>".strtotime($article['Date']).'</p>';
}
}
FROM:
http://bililite.com/blog/2012/06/05/new-bing-api/

you can use bellow code to get bing search results
$acctKey = 'Your 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>";

http://www.guguncube.com/2771/python-using-the-bing-search-api
it contains python code to query the bing and this is according to latest new API (Windows Azure Marketplace)
# -*- coding: utf-8 -*-
import urllib
import urllib2
import json
def main():
query = "sunshine"
print bing_search(query, 'Web')
print bing_search(query, 'Image')
def bing_search(query, search_type):
#search_type: Web, Image, News, Video
key= 'YOUR_API_KEY'
query = urllib.quote(query)
# create credential for authentication
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)'
credentials = (':%s' % key).encode('base64')[:-1]
auth = 'Basic %s' % credentials
url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/'+search_type+'?Query=%27'+query+'%27&$top=5&$format=json'
request = urllib2.Request(url)
request.add_header('Authorization', auth)
request.add_header('User-Agent', user_agent)
request_opener = urllib2.build_opener()
response = request_opener.open(request)
response_data = response.read()
json_result = json.loads(response_data)
result_list = json_result['d']['results']
print result_list
return result_list
if __name__ == "__main__":
main()

Don't forget to put this:
base64_encode("ignored:".$accountKey)
instead of:
base64_encode($accountKey . ":" . $accountKey)

Here is a working example of the Search API just replace "XXXX" with your access key. Even I wasted quite a few hours trying to get it to work using cURL but it was failing because of "CURLOPT_SSL_VERIFYPEER" on local :( - so make sure your cURL opts are set properly.
$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, base64_encode("username:XXXX"));
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);
# Deliver
return $response;
# Have a great day!
curl_close($process);

Here is the example of how to call Bing/Azure API using Unirest library.
require_once '/path/to/unirest-php/lib/Unirest.php';
$accountKey = "xxx";
$searchResults = Unirest::get("https://api.datamarket.azure.com/Bing/Search/v1/Composite",
array(),
array(
'Query' => '%27Microsoft%27',
'Sources' => '%27web%2Bimage%2Bvideo%2Bnews%2Bspell%27',
'$format' => 'json',
), $accountKey, $accountKey
);
// Results are here:
$objectArray = $searchResults->body->d->results;
$rawJson = $searchResults->raw_body;
You can omit Source parameter by defining it in the URL: https://api.datamarket.azure.com/Bing/Search/v1/Webor https://api.datamarket.azure.com/Bing/Search/v1/Image
Note: parameters in request URL are case-sensitive. For Bing they start with a capital letter.

Related

Translate array with google translator

I use below PHP code in Laravel to translate one sentence or paragraph from one input field:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . rawurlencode($name) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
and it works perfectly fine.
But now I have two input fields (name and description) and I want to translate both of those fields using one API call and show the results individually.
EDIT
I have tried to use array in the API request as below:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . array('sentence one', 'sentence two) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
But I get Array to string conversion error.
1Installing the Basic Client Libraries Client library PHP
composer require google/cloud-translate
and in your code
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationServiceClient = new TranslationServiceClient();
/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $textTwo = 'My name is John':
// $targetLanguage = 'fr'; // your lang
// $projectId = '[Google Cloud Project ID]';
$contents = [$text, $textTwo];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');
try {
$response = $translationServiceClient->translateText(
$contents,
$targetLanguage,
$formattedParent
);
// Display the translation for each input text provided
foreach ($response->getTranslations() as $translation) {
printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
}
} finally {
$translationServiceClient->close();
}
View Code in Github

Google Translate API v2, v3 PHP

I just started using the BING translate API to do a small volume of translations into most of their supported languages and that works pretty well.
There is a GitHub project that has simple PHP code for making the API call to Microsoft. You mostly just need the API key, and it can be customized pretty easily.
Text-Translation-API-V3-PHP
// NOTE: Be sure to uncomment the following line in your php.ini file.
// ;extension=php_openssl.dll
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
// Replace the subscriptionKey string value with your valid subscription key.
$key = 'ENTER KEY HERE';
$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";
// Translate to German and Italian.
$params = "&to=de&to=it";
$text = "Hello, world!";
if (!function_exists('com_create_guid')) {
function com_create_guid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
}
function Translate ($host, $path, $key, $params, $content) {
$headers = "Content-type: application/json\r\n" .
"Content-length: " . strlen($content) . "\r\n" .
"Ocp-Apim-Subscription-Key: $key\r\n" .
"X-ClientTraceId: " . com_create_guid() . "\r\n";
// NOTE: Use the key 'http' even if you are making an HTTPS request. See:
// http://php.net/manual/en/function.stream-context-create.php
$options = array (
'http' => array (
'header' => $headers,
'method' => 'POST',
'content' => $content
)
);
$context = stream_context_create ($options);
$result = file_get_contents ($host . $path . $params, false, $context);
return $result;
}
$requestBody = array (
array (
'Text' => $text,
),
);
$content = json_encode($requestBody);
$result = Translate ($host, $path, $key, $params, $content);
// Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
// We want to avoid escaping any Unicode characters that result contains. See:
// http://php.net/manual/en/function.json-encode.php
$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;
I also have a Google Cloud account and am looking for something similar for a few languages that Google supports that BING does not. For v2, it is not too hard to call Google to make the return the translations.
I found this GitHub project that seems to work for v2 API calls with an API key, but unfortunately I think that is a fee-for-service program now ?
google-cloud-php-translate
That also seems to work pretty well if you have an API key. If you are using v3, they apparently updated the libraries and support. You can make a CURL call from the command line and they have some of that documented on their website, but I am looking for a way to make the call using a PHP file.
require 'vendor/autoload.php';
use Google\Cloud\Translate\TranslateClient;
$translate = new TranslateClient([
'key' => 'APIKEY'
]);
// Translate text from english to french.
$result = $translate->translate('Hello world!', [
'target' => 'fr'
]);
echo $result['text'] . "\n";
// Detect the language of a string.
$result = $translate->detectLanguage('Greetings from Michigan!');
echo $result['languageCode'] . "\n";
// Get the languages supported for translation specifically for your target language.
$languages = $translate->localizedLanguages([
'target' => 'en'
]);
foreach ($languages as $language) {
echo $language['name'] . "\n";
echo $language['code'] . "\n";
}
// Get all languages supported for translation.
$languages = $translate->languages();
foreach ($languages as $language) {
echo $language . "\n";
}
Not sure that is even possible, but the best I can come up with is something like this based upon the command line CURL, but the authentication is wrong and fails. I do have the .json file for my Project/Service credentials. The ${PROJECT_ID} I presume is the project ID for the account, and Bearer $(gcloud auth application-default print-access-token) I am not sure about. There are some instructions about how to obtain that through the CLI, but is there a way to get that via a PHP file ? Like I say, the v2 version works fine.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global:detectLanguage");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n mimeType: 'text/plain',\n content: 'Omnia Gallia est divisa in tres partes'\n}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Authorization: Bearer $(gcloud auth application-default print-access-token)';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
echo $result;
}
curl_close ($ch);
There might be clues here, but it talks about exporting the path for the credentials file and running PHP scripts from the command line instead of from a server.
Google Cloud Translate API Samples
I have an irrational dislike for using client libraries, so I didn't install the Google PHP library. From what I can tell, the only way to get the authentication to work is to actually go through the whole Oauth2 process. I think the PHP library handles some of that for you, but this code should work as a standalone solution.
First, make sure you've got your Google Cloud Platform account set up, then create a project, then enable the Translation API, after that, create and configure an API key before creating and configuring an OAuth 2.0 client (make sure you enter the correct redirect url). Nothin' to it! ;-)
If you succeed in getting all of that squared away, you should be good to go!
The page effectively redirects the user to the same page they were just on, but includes the results of a GET request in the url. The response contains a code, that can be used to make another GET request in order to retrieve the access token, and once you've got the access token, you can make a POST request to perform the actual translation.
<?php
$clientId = "{your client id}";
$clientSecret = "{your client secret}";
$clientRedirectURL = "{your redirect URL}";
$login_url = 'https://accounts.google.com/o/oauth2/v2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-translation') . '&redirect_uri=' . urlencode($clientRedirectURL) . '&response_type=code&client_id=' . $clientId . '&access_type=online';
if (!isset($_GET['code'])){
header("location: $login_url");
} else {
$code = filter_var($_GET['code'], FILTER_SANITIZE_STRING);
$curlGet = '?client_id=' . $clientId . '&redirect_uri=' . $clientRedirectURL . '&client_secret=' . $clientSecret . '&code='. $code . '&grant_type=authorization_code';
$url = 'https://www.googleapis.com/oauth2/v4/token' . $curlGet;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
$data = json_decode($data, true);
curl_close($ch);
$accessToken = $data['access_token'];
$apiKey = "{your api key}";
$projectID = "{your project id}";
$target = "https://translation.googleapis.com/v3/projects/$projectID:translateText?key=$apiKey";
$headers = array(
"Content-Type: application/json; charset=utf-8",
"Authorization: Bearer " . $accessToken,
"x-goog-encode-response-if-executable: base64",
"Accept-language: en-US,en;q=0.9,es;q=0.8"
);
$requestBody = array();
$requestBody['sourceLanguageCode'] = "en";
$requestBody['targetLanguageCode'] = "pt";
$requestBody['contents'] = array("So, I guess this thing works?");
$requestBody['mimeType'] = "text/plain";
$ch = curl_init($target);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestBody));
$data = curl_exec($ch);
curl_close($ch);
echo $data;
}
Also, I found this tutorial quite helpful.
This probably won't evaluate:
'Authorization: Bearer $(gcloud auth application-default print-access-token)'
It's rather:
// $cmd = 'gcloud auth application-default login';
$cmd = 'gcloud auth application-default print-access-token';
$token = shell_exec($cmd);
besides it probably should be a service account.
It seems google/cloud replaces google/cloud-translate. For Translate, you could edit the translate-v2.json or add translate-v3beta1.json; but v3beta1 has a whole other REST API than v2 ...

VIMEO (Pro) get JSON response help (PHP/CURL)

I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);

PHP (CI) cURL passed multidimensional array does not behave as one (Can't loop it)

I'm having an extrange issue when receiving parameters from a POST cURL request. No matter how I encode it (json, url, rawurl, utf8, base64...) before POSTing it, I am not able to perform any decoding operation through the array elements, via loop. I'm giving you the details.
From the consuming controller, in some other php (Yii) app, I build my request like this:
private function callTheApi($options)
{
$url = "http://api.call.com/url/api";
$params = array( 'api_key' => $this->api_key,
'domain' => $this->domain,
'date' => $options['date'],
'keys' => $options['keys'] // This is an array
);
// Following some good advice from Daniel Vandersluis here:
// http://stackoverflow.com/questions/3772096/posting-multidimensional-array-with-php-and-curl
if (is_array($params['keys'])
{
foreach ($params['keys'] as $id => $name)
{
$params['keys[' . $id . ']'] = $name;
}
unset($params['keys']);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data; charset=utf-8'));
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en; rv:1.9.0.4) "
. "Gecko/2009011913 Firefox/3.0.6");
$output = curl_exec($ch);
$error = curl_errno($ch);
$error_text = curl_error($ch);
curl_close($ch);
if (!$output || $error != 0)
die("<br><hr>Problems...<br>"
. "Line:" . __LINE__ . " dataExtractor.php<br>"
. "Error: " . $error . " - " . $error_text . "<hr>"
. $url . "<hr>");
sleep(1);
return json_decode($output, true);
}
And in the api itself, this is the function:
public function api()
{
$params = $_POST;
foreach($params as $k=>$v){
if($k=='domain') $domain = $v;
if($k=='date') $date = $v;
if($k=='api_key') $api_key = $v;
if($k=='keys') $keys = $v;
}
echo json_encode($keys);
// All my logic would be here, after parsing the array correctly.
}
Ok, now for the problems:
If i leave everything like stated before, it works. I have my $keys array in the api, and I can use it however I want. The "echo json_encode($keys)" sentence returns the array ALMOST as it should be. But the problem is some values of the array are corrupted in the cURL operation. Values such as spanish characters á, é ,í, ó, ú OR ü are simply not present in the array_values.
If some key in the $keys array was spanish word "alimentación" in the original array, once it's been cURLed to the api, it becomes "alimentacin". There, the ó is not there anymore.
So, my chances are encoding each value in the array to a safely transferred value, so that I can decode it later. But what do you know, I can't.
I've tried urlencoding, rawurlencoding, json_encoding, base64_encoding... each value of the array. And if I return the received array from the api, it contains the encoded values all right. BUT.
If I loop the array in the api for decoding, and then try to return it, no matter what decoding function I'm applying to its values, the output is ALWAYS "NULL".
I have no clue what I'm doing wrong here. Not even close.
So any help would be much appreciated. Thanks in advance, community.
When you create cUrl params array you should know that keys cannot be utf8.
And when you add some parameters in foreach loop
$params['keys[' . $id . ']'] = $name;
$id can be utf8 character.
To avoid that I recommend you to use json_encode
$params = array(
'api_key' => $this->api_key,
'domain' => $this->domain,
'date' => $options['date'],
'keys' => json_encode($options['keys']) // This is an array
);
In your api in this case you should change nothing.

Problems with Twitter API 1.1 - application-only authentication response with PHP

I'm trying to retrieve data from Twitter by connecting to twitter API and make some requests the my code below but I get nothing in return... I just requested the bearer token and successfully received it.
This is the code in PHP:
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?
count=10&screen_name=twitterapi";
$headers = array(
"GET".$url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: My Twitter App v1.0.23",
"Authorization: Bearer ".$bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
$retrievedhtml = curl_exec ($ch); // execute the curl
print_r($retrievedhtml);
when using the print_r nothing is shown at all and when using the var_dump i find "bool(false)"
Any idea with what could be wrong with this?
Regards,
Try outputting any potential cURL errors with
curl_error($ch);
after the curl_exec command. That might give you a clue about what's going wrong. Completely empty responses usually point to something going wrong with the cURL operation itself.
Your headers are wrong... do not include
"GET".$url." HTTP/1.1"
in your headers.
Further, you may print out the HTTP return code by
$info = curl_getinfo($ch);
echo $info["http_code"];
200 is success, anything in the 4xx or 5xx range means something went wrong.
I built based on comments I found in a Twitter dev discussion by #kiers. Hope this helps!
<?php
// Get Token
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch,CURLOPT_POST, true);
$data = array();
$data['grant_type'] = "client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$screen_name = 'ScreenName'; // add screen name here
$count = 'HowManyTweets'; // add number of tweets here
$consumerKey = 'EnterYourTwitterAppKey'; //add your app key
$consumerSecret = 'EnterYourTwitterAppSecret'; //add your app secret
curl_setopt($ch,CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$bearer_token = json_decode($result);
$bearer = $bearer_token->{'access_token'}; // this is your app token
// Get Tweets
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count='.$count.'&screen_name='.$screen_name);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer ' . $bearer));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$cleanresults = json_decode($result);
// Release the Kraken!
echo '<ul id="twitter_update_list">';
foreach ( $cleanresults as $tweet ) {
// Set up some variables
$tweet_url = 'http://twitter.com/'.$screen_name.'/statuses/'.$tweet->id_str; // tweet url
$urls = $tweet->entities->urls; // links
$retweet = $tweet->retweeted_status->user->screen_name; // there is a retweeted user
$time = new DateTime($tweet->created_at); // lets grab the date
$date = date_format($time, 'M j, g:ia'); // and format it accordingly
$url_find = array();
$url_links = array();
if ( $urls ) {
if ( !is_array( $urls ) ) {
$urls = array();
}
foreach ( $urls as $url ) {
$theurl = $url->url;
if ( $theurl ) {
$url_block = ''.$theurl.'';
$url_find[] = $theurl; // make array of urls
$url_links[] = $url_block; // make array of replacement link blocks for urls in text
}
}
}
if ( $retweet ) { // add a class for retweets
$link_class = ' class="retweet"';
} else {
$link_class = '';
}
echo '<li'.$link_class.'>';
$new_text = preg_replace('##([\\d\\w]+)#', '$0', $tweet->text); // replace all #mentions with actual links
$newer_text = preg_replace('/#([\\d\\w]+)/', '$0', $new_text); // replace all #tags with actual links
$text = str_replace( $url_find, $url_links, $newer_text); // replace all links with actual links
echo $text;
echo '<br /><a class="twt-date" href="'.$tweet_url.'" target="_blank">'.$date.'</a>'; // format the date above
echo '</li>';
}
echo '</ul>';
I put together some files on github, named "Flip the Bird." Hope this helps...
I created PHP library supporting application-only authentication and single-user OAuth. https://github.com/vojant/Twitter-php.
Usage
$twitter = new \TwitterPhp\RestApi($consumerKey,$consumerSecret);
$connection = $twitter->connectAsApplication();
$data = $connection->get('/statuses/user_timeline',array('screen_name' => 'TechCrunch'));

Categories