Translate array with google translator - php

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

Related

Download a folder from azure blob storage which is not compressed in any format

I am trying to download a folder which is not compressed in any format like .zip,7-zip. I took code from Get azure blob files from inside Sub Directories using php.
My Folder structure on azure blob storage like that parentFolder>childFolder>1.pdf,2.pdf,3.pdf.
I am trying to download childFolder. I am using below code But I am getting error BlobNotFoundThe specified blob does not exist.
<?php
$storageAccount = 'XXXXXXX';
$containerName = 'XXXXXXX';
$blobName = 'parentFolder/childFolder';
$account_key = 'XXXXXXXXXXXXXXXXXXXXX';
$date = gmdate('D, d M Y H:i:s \G\M\T');
$version = "2019-12-12";
$stringtosign = "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:". $date . "\nx-ms-version:".$version."\n/".$storageAccount."/".$containerName."/".$blobName;
$signature = 'SharedKey'.' '.$storageAccount.':'.base64_encode(hash_hmac('sha256', $stringtosign, base64_decode($account_key), true));
echo "\n\n" . $signature;
$header = array (
"x-ms-date: " . $date,
"x-ms-version: " . $version,
"Authorization: " . $signature
);
$url="https://$storageAccount.blob.core.windows.net/$containerName/$blobName";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
curl_exec ( $ch );
$result = curl_exec($ch);
echo "\n\n" . $result;
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
file_put_contents('C://demo//childFolder', $result); // save the string to a file
curl_close($ch);
Just try the code below that using sasToken and cURL to download all blobs under a folder:
<?php
function generateSharedAccessSignature($accountName,
$storageKey,
$signedPermissions,
$signedService,
$signedResourceType,
$signedStart,
$signedExpiry,
$signedIP,
$signedProtocol,
$signedVersion){
if(empty($accountName)){
trigger_error("The account name is required.");
return;
}
if(empty($storageKey)){
trigger_error("The account key is required.");
return;
}
if(empty($signedPermissions)){
trigger_error("The permissions are required.");
return;
}
if(empty($signedService)){
trigger_error("The services are required.");
return;
}
if(empty($signedResourceType)){
trigger_error("The resource types are required.");
return;
}
if(empty($signedExpiry)){
trigger_error("The expiration time is required.");
return;
}
if(empty($signedVersion)){
trigger_error("The service version is required.");
return;
}
// generate the string to sign
$_toSign = urldecode($accountName) . "\n" .
urldecode($signedPermissions) . "\n" .
urldecode($signedService) . "\n" .
urldecode($signedResourceType) . "\n" .
urldecode($signedStart) . "\n" .
urldecode($signedExpiry) . "\n" .
urldecode($signedIP) . "\n" .
urldecode($signedProtocol) . "\n" .
urldecode($signedVersion) . "\n";
// sign the string using hmac sha256 and get a base64 encoded version_compare
$_signature = base64_encode(hash_hmac("sha256", utf8_encode($_toSign), base64_decode($storageKey), true));
return $_signature;
}
$key= "";
$storageAccount = "";
$containerName = "";
$directoryName = "";
$destDir = "d:/temp/";
$_signedPermissions = "rl"; //read and list permission
$_signedService = "b"; // for blob service
$_signedResourceType = "oc"; //only for access container and object
$_signedStart = "2021-05-31T00:00:00Z"; //sas token start time
$_signedExpiry = "2021-06-10T00:00:00Z"; //sas token expairy time
$_signedIP = NULL; // no IP limit
$_signedProtocol = "https";
$_signedVersion = "2020-02-10";
$_signature = generateSharedAccessSignature($storageAccount,
$key,
$_signedPermissions,
$_signedService,
$_signedResourceType,
$_signedStart,
$_signedExpiry,
$_signedIP,
$_signedProtocol,
$_signedVersion);
$sig = urlencode($_signature);
$sasToken = "sp=$_signedPermissions&srt=$_signedResourceType&ss=$_signedService&st=$_signedStart&se=$_signedExpiry&sv=$_signedVersion&spr=$_signedProtocol&sig=$sig";
$destinationURL = "https://$storageAccount.blob.core.windows.net/$containerName?restype=container&comp=list&prefix=$directoryName&$sasToken";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $destinationURL);
$content = curl_exec($ch);
$xml = simplexml_load_string($content);
foreach ($xml->Blobs->Blob as $i) {
$url ="https://$storageAccount.blob.core.windows.net/$containerName/$i->Name";
//Use basename() function to return the base name of file
$file_name = $destDir.basename($url) ;
//Use file_get_contents() function to get the file
//from url and use file_put_contents() function to
//save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url."?".$sasToken ))) {
echo "$url:File downloaded successfully\n";
}
else {
echo "File downloading failed.";
}
}
?>
I have tested on my side, see result below:
my blobs :
Your approach will not work because the folders in Azure Blob Storage are not real folders. They are virtual folders. Your blob names are parentFolder/childFolder/1.pdf and so on.
To download blobs from a virtual folder, here's what you would need to do:
List blobs in your blob container. Since you only want to download blobs from parentFolder/childFolder, you will have to do prefix search. That will list all the blobs in the desired folder.
Once you have the list, then you can download each blob from that list.
Unfortunately I am not that much knowledgeable about PHP thus I am only giving you some guidance (and not code).
I would also recommend using Azure Storage SDK for PHP instead of consuming the REST API directly. That will make your job much easier. You can find more information about the SDK here: https://github.com/Azure/azure-storage-php.

How to put URL string in json Viber API php

I am a newbie developer trying to learn web development. I am currently working on this project where articles from a website get shared automatically to a viber public chat. I am facing this problem where I cannot put the URL in the media. I think this is because its json. I am not sure what I am doing wrong here. I have included.
<?php
$Tid = "-1";
if (isset($_GET['id'])) {
$Tid = $_GET['id'];
}
$url = 'https://chatapi.viber.com/pa/post';
$jsonData='{
"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from": "K9/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media": "$thisID"
// I want to use $thisID as shown above. But when I
do so this error appears [ {"status":3,"status_message":"'media' field value is not a valid url."} ]
// When I use any full form url like https://google.com it works fine
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
?>
This would work as you are using a single quoted literal.
"media": "' . $thisID . '"
But you are always better to make a PHP array or Object and then use json_encode() to create the JSON String like this
$obj = new stdClass;
$obj->auth_token = "4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813";
$obj->from = "K9/C2Vz12r+afcwZaexiCg==";
$obj->type = 'url';
$obj->media = $thisID;
$jsondata = json_encode($obj);
RESULT of echo $jsondata;
{"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from":"K9\/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media":"-1"
}

How to remove unwanted characters from Guzzlehttp json reposnce

Hi I am new to Laravel and have tried several turtorials on Goutte on Guzzelhttp but I am still unable to figure out how to remove 3 unwanted charactures from the begining of the json responce as shown here using curl and json_decode.
$url = "URL to atom feed";
$user = "user";
$pass = "pass";
// using CURL to get our results
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
$output = curl_exec($ch);
curl_close($ch);
// decoding our results into an associative array
// doing a substring as there are 3 weird characters being passed back from IIS in front of the string
$data = json_decode(substr($output, 3, strlen($output)), true);
// grabbing our results object
$list = $data['$resources'];
I have in my ScrapeController,
<?php
// app/controllers/ScrapeController.php
class ScrapeController extends BaseController {
public function getIndex() {
echo "Scrape index page.";
}
public function getNode($node) {
echo "Scraped page $node";
}
public function getPages() {
$client = new GuzzleHttp\Client();
$res = $client->get('URL to atom feed', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode();
// "200"
// echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
this is what I have tried $res->getBody(substr($res, 3, strlen($res));without any luck I am unable to find any answers to this problem on guzzle documents page save to say any custom json_decode option should be preformed in the getBody() option.
You need to do
$body = substr($res->getBody(), 3)
instead of
$body = $res->getBody(substr($res, 3, strlen($res))
I recently found this piece of code on github by Colin Viebrock,
$client = new Guzzle\Http\Client('http://example.com');
$client->addSubscriber( new Cviebrock\Guzzle\Plugin\StripBom\StripBomPlugin() );
$request = $client->get('some/request');
$response = $client->send($request);
$data = $response->json();
works a treat in laravel hope this helps anyone how gets "Unable to parse response body into JSON: 4" using Guzzle.

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'));

How to use Constant Contact API?

I want to use API of the constant contact and want to insert user email using PHP while user register to the site.
please reply if any help.
Thanks in advance.
// fill in your Constant Contact login and API key
$ccuser = 'USERNAME_HERE';
$ccpass = 'PASS_HERE';
$cckey = 'APIKEY_HERE';
// fill in these values
$firstName = "";
$lastName = "";
$emailAddr = "";
$zip = "";
// represents the contact list identification number(s)
$contactListId = INTEGER_OR_ARRAY_OF_INTEGERS_HERE;
$contactListId = (!is_array($contactListId)) ? array($contactListId) : $contactListId;
$post = new SimpleXMLElement('<entry></entry>');
$post->addAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$title = $post->addChild('title', "");
$title->addAttribute('type', 'text');
$post->addChild('updated', date('c'));
$post->addChild('author', "");
$post->addChild('id', 'data:,none');
$summary = $post->addChild('summary', 'Contact');
$summary->addAttribute('type', 'text');
$content = $post->addChild('content');
$content->addAttribute('type', 'application/vnd.ctct+xml');
$contact = $content->addChild('Contact');
$contact->addAttribute('xmlns', 'http://ws.constantcontact.com/ns/1.0/');
$contact->addChild('EmailAddress', $emailAddr);
$contact->addChild('FirstName', $firstName);
$contact->addChild('LastName', $lastName);
$contact->addChild('PostalCode', $zip);
$contact->addChild('OptInSource', 'ACTION_BY_CUSTOMER');
$contactlists = $contact->addChild('ContactLists');
// loop through each of the defined contact lists
foreach($contactListId AS $listId) {
$contactlist = $contactlists->addChild('ContactList');
$contactlist->addAttribute('id', 'http://api.constantcontact.com/ws/customers/' . $ccuser . '/lists/' . $listId);
}
$posturl = "https://api.constantcontact.com/ws/customers/{$ccuser}/contacts";
$authstr = $cckey . '%' . $ccuser . ':' . $ccpass;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/atom+xml"));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
curl_close($ch);
// returns true on success, false on error
return (!is_numeric($response));
The developers of ConstantContact have launched PHP library to handle such kind of tasks.
Following version is for older PHP versions (5.2 or lesser). Download code from here: https://github.com/constantcontact/ctct_php_library
Following is an example to add a subscriber's email in your constant contact lists.
After downloading the above library, use following code to add an email in Constant Contact list(s).
session_start();
include_once('ConstantContact.php'); // Set path accordingly
$username = 'YOUR_CONSTANT_CONTACT_USER_NAME';
$apiKey = 'YOUR_API_KEY';
$password = 'YOUR_CONSTANT_CONTACT_PASSWORD';
$ConstantContact = new Constantcontact("basic", $apiKey, $username, $password);
$emailAddress = "new_email#test.com";
// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);
// If the search did not return a contact object
if($search == false){
$Contact = new Contact();
$Contact->emailAddress = $emailAddress;
//$Contact->firstName = $firstName;
//$Contact->lastName = $lastName;
// represents the contact list identification link(s)
$contactList = LINK_OR_ARRAY_OF_LINKS_HERE;
// For example,
// "http://api.constantcontact.com/ws/customers/USER_NAME/lists/14";
$Contact->lists = (!is_array($contactList)) ? array($contactList) : $contactList;
$NewContact = $ConstantContact->addContact($Contact);
if($NewContact){
echo "Contact Added. This is your newly created contact's information<br /><pre>";
print_r($NewContact);
echo "</pre>";
}
} else {
echo "Contact already exist.";
}
Note: The latest version can be found on the GitHub links given in following URL: http://developer.constantcontact.com/libraries/sample-code.html
But I am not sure if the above example code works with the newer library or not.
If you can't get this to work, you might have to add this curl_setopt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

Categories