automatic change text into other language + google translator - php

In my PHP application there a new functionality I have to develop that is when user fill sign in form(html),whatever he/she put in "Name" field other two fileds i.e. "name in traditional Chinese" and "name in Chinese" should automatically filled.
I want to know is it possible with google translator? if yes then please share with me code or example.

Assuming that you want the translations perfomed on the server side (PHP) you can use file_get_contents to fetch data from Google Translate API. Then you need to parse the response and get translated text. You need to get API KEY to access the Translate service.
<?php
$string = 'Hello World';
$source_lang = 'en';
$target_lang = 'zh-CN'
header ( "Content-Type: text/html;charset=utf-8" );
$data = file_get_contents ( 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q='.urlencode($string).'&source='.$source_lang.'&target='.$target_lang );
$data = json_decode ( $data );
$translated = $data->data->translations->[0]->translatedText;
echo $translated;
?>
Server responses are JSON objects with that structure:
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt",
"detectedSourceLanguage": "en"
}
]
}
}
More info about basic concept is avaliable on:
http://baris.aydinoglu.info/coding/google-translate-api-in-php.
Documentation of Google Translate API queries:
http://code.google.com/apis/language/translate/v2/using_rest.html

Related

Displaying Output from Basic API (PHP)

So I am using an API (SendInBlue - a transactional email service) and I am trying to use the API to display a list of the users on my webpage.
Below, SendInBlue has given me sample code to use, however when I put them together I just get a blank screen.
I know this is a total beginner question... but how do I put these 2 pieces of code together so that it actually displays the list of contacts on my website?
Thank you so much!!
EXAMPLE
require('../mailin.php');
$mailin = new Mailin("https://api.sendinblue.com/v2.0","your access key");
$data = array( "listids" => array(1,2),
"timestamp" =>"2015-05-22 14:30:00",
"page" => 1,
"page_limit" => 2
);
var_dump($mailin->display_list_users($data));
SAMPLE OUTPUT
{
"code":"success",
"message":"Retrieved details of all users for the given lists",
"data":{
"data":[
{
"blacklisted":0,
"email":"email1#domain.com",
"id":1,
"listid":[1],
"blacklisted_sms":1,
"last_modified" : "2015-05-22 15:30:00"
},
{
"blacklisted":1,
"email":"email2#domain.com",
"id":2,
"listid":[1,2],
"blacklisted_sms":0 ,
"last_modified" : "2015-05-25 19:10:30"
}
],
"page":1,
"page_limit":2,
"total_list_records":100
}
}
Ok I figured this out. I turned every attribute into a variable like so...
$subscriberemail = $getemails['data']['data'][$number]['email'];
This took ages to figure out!

deserialize wordpress custom field in json api plugin

In my wordpress theme there is a custom post type named songs and in that post type there is a custom field named playlist which contain songs information like artist name,download link,song lyric etc...
My problem is that this custom field is serialized in json version of my website
and i don't know how to fix that.
I use json api plugin for word press.
here is an example of what it shows in json
...
"custom_fields": {
...
"playlist": [
"a:1:{i:0;a:19:{s:5:\"title\";s:44:\"Hosein Tohi And Sami Beigi - Ba Man Miraghsi\";s:3:\"mp3\";s:134:\"http:\/\/dl.paradi3emusic.com\/Musics\/Aban%2094\/Persian\/Single\/Hosein%20Tohi%20And%20Sami%20Beigi%20-%20Ba%20Man%20Miraghsi%20-%20128.mp3\";s:7:\"radioip\";s:0:\"\";s:9:\"radioport\";s:0:\"\";s:11:\"buy_title_a\";s:14:\"\u06a9\u06cc\u0641\u06cc\u062a 320\";s:10:\"buy_icon_a\";s:14:\"cloud-download\";s:10:\"buy_link_a\";s:134:\"http:\/\/dl.paradi3emusic.com\/Musics\/Aban%2094\/Persian\/Single\/Hosein%20Tohi%20And%20Sami%20Beigi%20-%20Ba%20Man%20Miraghsi%20-%20320.mp3\";s:11:\"buy_title_b\";s:14:\"\u06a9\u06cc\u0641\u06cc\u062a 128\";s:10:\"buy_icon_b\";s:14:\"cloud-download\";s:10:\"buy_link_b\";s:134:\"http:\/\/dl.paradi3emusic.com\/Musics\/Aban%2094\/Persian\/Single\/Hosein%20Tohi%20And%20Sami%20Beigi%20-%20Ba%20Man%20Miraghsi%20-%20128.mp3\";s:11:\"buy_title_c\";s:0:\"\";s:10:\"buy_icon_c\";s:14:\"cloud-download\";s:10:\"buy_link_c\";s:0:\"\";s:11:\"buy_title_d\";s:0:\"\";s:10:\"buy_icon_d\";s:14:\"cloud-download\";s:10:\"buy_link_d\";s:0:\"\";s:10:\"buy_custom\";s:0:\"\";s:11:\"lyric_title\";s:0:\"\";s:5:\"lyric\";s:0:\"\";}}"
],
...
},
...
****EDIT*****
I want to have another custom field which contain json array of these serialized data but unserialized
also I tried this but didn't worked.
add_post_meta($id, 'myplaylist1', $playlist);
You will need to write a filter to deserialize the content before it is output by the json api plugin.
There is a filter applied by the plugin just before the json is output, documented here:
https://en-gb.wordpress.org/plugins/json-api/other_notes/#5.-Extending-JSON-API
That would be suitable for this task.
Add the following to your themes functions.php:
add_filter('json_api_encode', function($response){
if (isset($response['posts'])) {
foreach ($response['posts'] as $post) {
deserialize_playlist($post);
}
} else if (isset($response['post'])) {
deserialize_playlist($response['post']);
}
return $response;
});
function deserialize_playlist(&$post) {
if(isset($post->custom_fields->playlist)){
$playlists = $post->custom_fields->playlist;
//custom fields appear to always be returned as an array
foreach($playlists as &$playlist){
$playlist = unserialize($playlist);
}
$post->custom_fields->playlist = $playlists;
}
}
You can use wordpress built in maybe_unserialize() function to unserialize a serialize data
https://codex.wordpress.org/Function_Reference/maybe_unserialize

Facebook language codes table

If I'm adding like-box or page-plugin so I have to choose the language in which it will be displayed.
But what if I have multilanguage-site system in PHP which remembers only country codes (en,es...). So I probably need a table like this, but with all languages:
en => en_US
es => es_ES ...
Do you know about some?
Facebook is using country codes, but this codes are a bit more specific so they are mostly called Locale ID (language and country code).
You could just grab the XML from facebook with all locale ids used by them:
<locale>
<englishName>English (UK)</englishName>
<codes>
<code>
<standard>
<name>FB</name>
<representation>en_GB</representation>
</standard>
</code>
</codes>
</locale>
You can find the whole file here (https://www.facebook.com/translations/FacebookLocales.xml)
BUT:
The Problem here is, that you cannot refer from en to en_US or en_GB. So the mapping from 2 to 4 letters won't work. You need to have a table with the language and country code like en_US.
Most modern browser send an "accept language" header, but beware It's not 100% reliable and it's just the primary language of the users browser and not really the country code.
try: var_dump( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
to get: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
You can also try to use an API i.e. http://www.hostip.info/
An example would be:
$theFirstPart = "en";// you said you already got this
$userIP = "12.215.42.19";// from $_SERVER var
$languageCode = "en_US";// your standard
//you should use curl for this
// and it's really slow, so please cache this for at least a day or two ;)
$content = file_get_contents( "http://api.hostip.info/get_json.php?ip=$userIP" );
if( $content ) {
$json = json_decode( $content );
if( $json && isset( $json->country_code ) ) {
// before you assign the value, you should check if it's in the facebook xml
$languageCode = $theFirstPart.'_'.$json->country_code;
}
echo "<pre>";
var_dump( $languageCode );
}
Finally I created this table from all supported facebok lang-locales then I picked one using stripos() and because it few-times picked up wrong code, I re-ordered the array by putting prefered to top of the array.
Maybe it's not the best solution, but it solved my problem.
function fb_lang($lang_code){
$fb_locales = [
'es_ES', 'en_US', 'fr_FR', 'tr_TR', 'sv_SE', // prefered codes are moved to line
'af_ZA', 'sq_AL', 'ar_AR', 'hy_AM', 'ay_BO', 'az_AZ', 'eu_ES', 'be_BY', 'bn_IN', 'bs_BA', 'bg_BG', 'ca_ES', 'ck_US',
'hr_HR', 'cs_CZ', 'da_DK', 'nl_NL', 'nl_BE', 'en_PI', 'en_GB', 'en_UD', 'eo_EO', 'et_EE', 'fo_FO', 'tl_PH', 'fi_FI',
'fb_FI', 'fr_CA', 'gl_ES', 'ka_GE', 'de_DE', 'el_GR', 'gn_PY', 'gu_IN', 'he_IL', 'hi_IN', 'hu_HU', 'is_IS', 'id_ID',
'ga_IE', 'it_IT', 'ja_JP', 'jv_ID', 'kn_IN', 'kk_KZ', 'km_KH', 'tl_ST', 'ko_KR', 'ku_TR', 'la_VA', 'lv_LV', 'fb_LT', 'li_NL',
'lt_LT', 'mk_MK', 'mg_MG', 'ms_MY', 'ml_IN', 'mt_MT', 'mr_IN', 'mn_MN', 'ne_NP', 'se_NO', 'nb_NO', 'nn_NO', 'ps_AF', 'fa_IR',
'pl_PL', 'pt_BR', 'pt_PT', 'pa_IN', 'qu_PE', 'ro_RO', 'rm_CH', 'ru_RU', 'sa_IN', 'sr_RS', 'zh_CN', 'sk_SK', 'sl_SI', 'so_SO',
'es_LA', 'es_CL', 'es_CO', 'es_MX', 'es_VE', 'sw_KE', 'sy_SY', 'tg_TJ', 'ta_IN', 'tt_RU', 'te_IN', 'th_TH',
'zh_HK', 'zh_TW', 'uk_UA', 'ur_PK', 'uz_UZ', 'vi_VN', 'cy_GB', 'xh_ZA', 'yi_DE', 'zu_ZA'
];
foreach($fb_locales as $fbl){
if(stripos($fbl,$lang_code)!==false){
return $fbl;
}
}
trigger_error('Fb_lang() couldn\'t find equvalent for language code "'.$lang_code.'"');
return 'en_US';
}
Hope it will help someone else.

Google API URL return no results

I need a PHP Google search function, so I tried many function I found in Google, but almost all have the same problem which is they take results directly from Google main URL not from the API URL, which lead after a while to an error because Google detect the visits are from a PHP server and reject any further requests.
So I made my Google search function takes results from Google API URL, and that worked perfectly as you see here #API_URL until I needed to reduce the results buy adding intitle: before the searched keyword, and now the API URL return no result at all as you see here #API_URL.
My question is simple, how do I get results in the Google API URL using this query intitle:maleficent+2014+site:www.anakbnet.com/video/file.php?f= so that I can take Results from it using PHP?
The data you get back from your 'Google API' call is json encoded data so you should try something like the following:-
/* define a constant for ease */
define('BR','<br />');
$data='{"responseData": {"results":[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://www.anakbnet.com/video/file.php?f\u003d1452","url":"http://www.anakbnet.com/video/file.php%3Ff%3D1452","visibleUrl":"www.anakbnet.com","cacheUrl":"http://www.google.com/search?q\u003dcache:9-JgVUvjnGYJ:www.anakbnet.com","title":"مشاهدة فيلم Alexander and the Terrible اون لاين مباشرة بدون تحميل \u003cb\u003e...\u003c/b\u003e","titleNoFormatting":"مشاهدة فيلم Alexander and the Terrible اون لاين مباشرة بدون تحميل ...","content":"29 كانون الثاني (يناير) 2015 \u003cb\u003e...\u003c/b\u003e مشاهدة فيلم \u003cb\u003eMaleficent 2014\u003c/b\u003e DVD HD مترجم اون لاين مباشرة بدون تحميل اكشن ,مغامرة \n,عائلي .. مشاهدة افلام اجنبية مترجمة اونلاين كاملة. (مشاهدة: 491,605 )."}],"cursor":{"resultCount":"1","pages":[{"start":"0","label":1}],
"estimatedResultCount":"1",
"currentPageIndex":0,
"moreResultsUrl":"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dmaleficent+2014+site:www.anakbnet.com/video/file.php?f%3D",
"searchResultTime":"0.09"}},
"responseDetails": null,
"responseStatus": 200}';
$json=json_decode( $data, true );
$res=(object)$json['responseData']['results'][0];
/* two items extracted from data - use same methodology to get other items */
echo $res->unescapedUrl;
echo $res->cacheUrl;
echo '<pre>';
foreach( $json as $key => $param ){
echo $key.BR;
if( is_array( $param )) $param=(object)$param;
print_r( $param );
}
echo '</pre>';
Hopefully from that you can find what you want?!

Obtain a Blogger's blog ID from its friendly URL without screen scraping

I'm using the Blogger API for PHP. I want to obtain the blog ID from just the site's name.
For example, http://sleeptalkinman.blogspot.com/ has a blog ID of 3117168333067506122. This is possible as the blog ID appears in the source, but screen scraping isn't a good idea!
Is it possible to obtain it through the API instead of scraping it from the HTML?
Today, the newest blogger API is in version 3.0. With that new API, we can get blog ID with resource type getByUrl. This is full example using my blog and my API:
https://www.googleapis.com/blogger/v3/blogs/byurl?url=http%3A%2F%2Fwww.ifaniqbal.com&key=AIzaSyDNkR52eSfObZi9BPKrTytbowOAM7Js9uY
Just Ctrl+C that example and Ctrl+V to your browser to test that. One of return field of that example is 'id' field, which is the blog ID that we want (in JSON), like this:
{
"kind": "blogger#blog",
"id": "7107469463017369923",
"name": "Ifan Iqbal",
"description": "Tips, Download, Resensi, Tutorial, Blog, Blogspot",
"published": "2012-02-28T23:54:48+07:00",
"updated": "2013-07-11T16:24:58+07:00",
"url": "http://www.ifaniqbal.com/",
"selfLink": "https://www.googleapis.com/blogger/v3/blogs/7107469463017369923",
"posts": {
"totalItems": 161,
"selfLink": "https://www.googleapis.com/blogger/v3/blogs/7107469463017369923/posts"
},
"pages": {
"totalItems": 2,
"selfLink": "https://www.googleapis.com/blogger/v3/blogs/7107469463017369923/pages"
},
"locale": {
"language": "in",
"country": "",
"variant": ""
}
}
(I had posted an original answer, but modified it to use Zend_Gdata instead).
Here is a method of getting the blog ID.
<?php
$user = 'username';
$pass = 'password';
// I have to admit, I would normally use the autoloader
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Feed');
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'blogger', null,
Zend_Gdata_ClientLogin::DEFAULT_SOURCE, null, null,
Zend_Gdata_ClientLogin::CLIENTLOGIN_URI, 'GOOGLE');
$gdClient = new Zend_Gdata($client);
/**
* Get the blog ID
* #param string $feed URL to blog feed or blog name
* Example:
* - http://googleblog.blogspot.com/feeds/posts/default
*/
function getBlogId($gdClient, $feed)
{
// You could build the /feed/posts/default part yourself and just pass
// googleblog.blogspot.com:
// $feed = 'http://' . $feed . '/feeds/posts/default';
$query = new Zend_Gdata_Query($feed);
$feed = $gdClient->getFeed($query);
preg_match('/blog-([0-9]+)/', $feed->id->text, $match);
if (isset($match[1]))
{
return $match[1];
}
return false;
}
echo getBlogId($gdClient, 'http://sleeptalkinman.blogspot.com/feeds/posts/default');
Original answer
If you're trying to retrieve information, then you should simply be able to replace the www.blogger.com part and ignore the blogID. For example, if you're trying to find all posts from http://dailyvim.blogspot.com/ you would use:
http://dailyvim.blogspot.com/feeds/posts/default
Instead of the normal URL, http://www.blogger.com/feeds/[blogID]/posts/default
This method may also work for publishing to the blog, so long as the authenticated user has write access to it. I have not been able to test this, though.
Getting the blog ID
You can get the blog ID from the feed above using the following:
$content = file_get_contents('http://sleeptalkinman.blogspot.com/feeds/posts/default');
preg_match('/<id>.*blog-([0-9]+)</id>/U', $content, $match);
print $match[1]; // Prints the blog ID
Getting post IDs for latest posts
You can also get the latest posts from the above feed (this time I'll use SimpleXML instead):
$feed = simplexml_load_file('http://sleeptalkinman.blogspot.com/feeds/posts/default');
foreach ($feed->entry as $entry)
{
// I'm getting both the blog ID and post ID
preg_match('/blog-([0-9]+).*post-([0-9]+)/', $entry->id, $match);
print $match[2];
// Now you can use the following URL with the blogger API
$comment_feed_url = 'http://www.blogger.com/feeds/' . $match[1] . '/' . $match[2] . '/comments/default';
}
$blog = "sleeptalkinman.blogger.com";
$username = split('\.', $blog)[0];
should give you what you're after, as long as you have the URL like above.
Seems you can use the blog's url to get the comments as well, try;
http://someusername.blogspot.com/feeds/comments/default
And you can get all the comments for a given post in the similar way, namely /feeds/xxxxxxxx/comments/default, where xxxxxxxx is the post ID.
And you can qualify by date by using the query string ?published-min=2010-03-16T00:00:00&published-max=2010-03-24T23:59:59
As a side note, the Blogger API can return the feed as JSON rather than XML, which I found way easier to deal with than parsing XML by using the query string ?alt=json

Categories