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?!
Related
I am using Facebook API to fetch the full Ads list.
The Code is working, But it return only 25 Ad in case of i have 150+ Ad in my account.
I guess that happens because of the query limits on the Facebook API.
My Code:
$account = new AdAccount('act_<AD_ACCOUNT_ID>');
$account->read();
$fields_adset = array(
AdSetFields::ID,
AdSetFields::NAME,
AdSetFields::CAMPAIGN_ID,
AdSetFields::STATUS,
);
$ads = $account->getAds($fields_adset);
foreach ($ads as $adset) {
$adset_id = $adset->{AdSetFields::ID};
echo $adset_id;
//print_r($adset);
//exit();
}
So, they mentioned in the documentation that :
Use Asynchronous Requests to query a huge amount of data
Reference (1) : https://developers.facebook.com/docs/marketing-api/best-practices/
Reference (2) : https://developers.facebook.com/docs/marketing-api/insights/best-practices/#asynchronous
But, I can't apply that "Asynchronous" requests to my code to fetch the Full Ad List,
Please help me to fetch the full Ads list
Thank you.
You should implement pagination (or request a limit more high). With the PHP SDK you can implement the cursor as described in the doc here or more simply set the Implicit Fetching, as example:
..
use FacebookAds\Cursor;
...
Cursor::setDefaultUseImplicitFetch(true);
$account = new AdAccount('act_<AD_ACCOUNT_ID>');
$account->read();
$fields_adset = array(
AdSetFields::ID,
AdSetFields::NAME,
AdSetFields::CAMPAIGN_ID,
AdSetFields::STATUS,
);
$ads = $account->getAds($fields_adset);
foreach ($ads as $adset) {
$adset_id = $adset->{AdSetFields::ID};
echo $adset_id;
//print_r($adset);
//exit();
}
Hope this help
I am currently finishing the website for my client and the only feature and I can't implement is to show the right phone number to a user based on the location.
I tried to find some plugins but no success. Maybe someone can help me with the piece of code I can implement this feature? Thanks!
A couple things.
Since geolocation can be spoofed, ideally you would display all available numbers and have a main number. Or even better have call tracking numbers that are changed via script based on visitor acquisition and referral source.
Barring all of that, you can use a resource like ipstack
You make a request to https://api.ipstack.com/ with the IP Address you want to use ( potentially $_SERVER['REMOTE_ADDR']?) and your access key. So your request URL would like like the following:
$ipstack_url = 'https://api.ipstack.com/123.456.789.001?access_key=YOURACCESSKEYHERE'
WordPress has a built in remote URL function wp_remote_get() that you can use to get this value.
$geo_info = wp_remote_retrieve_body( wp_remote_get( $ipstack_url ) );
To be nice to ipstack (and your request limit), you should probably cache this with the WP_Transients API for at least 24 hours (these results won't change much, so you could cache even longer if you want). You get 10k requests a month for free, so if you have a high traffic site, this is even more important
Now you can do what you want with the ipstack request for that IP address, like display a different phone number based on the current city.
If we combine all of that, you get something like this:
// Get your IP however you want
$ip_addr = $_SERVER['REMOTE_ADDR'];
// You'll need an API Key
$api_key = 'YOURACCESSKEYHERE';
// Build your API URL
$api_url = "https://api.ipstack.com/$ip_addr?access_key=$api_key"; // Build the API Url
// Give your transient a unique, yet identifiable name
$transient_name = "ipstack-$ip_addr";
// Check for our transient, if it's not there set it for 24 hours
if( false === ( $transient = get_transient( $transient_name ) ) ){
set_transient( $transient_name, wp_remote_retrieve_body( wp_remote_get( $api_url ) ), 86400 );
}
// Decode the JSON response we got
$json = json_decode( get_transient( $transient_name ) );
// Do whatever you want with it
if( $json->city == 'Los Angeles' ){
echo 'Phone For LA: 123-456-7890';
} else if( $json->city == 'San Francisco' ){
echo 'Phone For SF: 321-654-0987';
} else {
echo 'Default Phone: 098-765-4321';
}
Some basic background: I help run a gaming channel on YouTube, and I'm building a utility (using PHP) to integrate the channel's content with a companion website. Our playlists are primarily "let's play" series ordered by publication date that follow chronological progress through various games, and I would like the website to display the "latest episode" from a select number of series.
I know that I can work my way to the last video by chaining calls to the following:
$youtubeService->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId
"pageToken" => $nextPageToken
)
)
And simply grab the last item in the response set when $nextPageToken is unset.
However, this strikes me as incredibly inefficient--partly because I believe it eats away at my API request quota, but mostly because it's going to slow down the overall response time of the site. Neither of those are ideal.
It seems like there should be an easier way to grab the "latest" video in a playlist either by changing the order of the response, or with some handy function, but I can't find any documentation on it.
I've looked at using the Search functions over the PlaylistItems, but (according to the documentation), Search only accepts Channel IDs as a parameter and not Playlist IDs, which makes me think that its the wrong direction to head.
The short answer here is that this appears to be impossible under the current version of the API. There is no apparent way to essentially select videos in reverse, but I did make a minor change which resulted in whole process being a tad more efficient.
This is the original code:
$items = $youtube->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId,
"maxResults" => 50
)
);
while ($items->nextPageToken) {
$items = $youtube->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId,
"maxResults" => 50,
"pageToken" => $items->nextPageToken
)
);
}
if ($items) {
return end($items->getItems());
}
This is the fix:
First, I added an object to assist with caching:
class PlaylistCache {
protected $expirationDate;
protected $playlistId;
protected $latestEpisode;
__construct($playlistId, $latestEpisode) {
$this-playlistId = $playlistId;
$this->latestEpisode = $latestEpisode;
$this->expirationDate = time() + 86400;
// get current time + 24 hours
}
public function getLatestEpisode() {
return $this->latestEpisode;
}
public function getPlaylistId() {
return $this->playlistId;
}
public function isExpired() {
return $this->expirationDate < time();
}
}
Then, before polling the API, I look to see if I have a cached version available, and I only resort to the API if that cached version is expired.
$playlistCache = json_decode(get_option('playlist_cache_' . $playlistId));
if ($playlistCache->isExpired()) {
$items = $youtube->playlistItems->listPlaylistItems(
"id",
array(
"playlistId" => $playlistId,
"maxResults" => 50
)
);
while ($items->nextPageToken) {
$items = $youtube->playlistItems->listPlaylistItems(
"id",
array(
"playlistId" => $playlistId,
"maxResults" => 50,
"pageToken" => $items->nextPageToken
)
);
}
if ($items) {
$videoId = end($items->getItems()[0]->getId());
$video = $youtube->videos->listVideos("snippet", array('id' => $videoId))
$video = $video->getItems()[0];
$playlistCache = new PlaylistCache($playlistId, $video);
update_option('playlist_cache_' . $playlistId, json_encode($playlistCache)));
}
}
return $playlistCache->getLatestEpisode();
The other big change here is that my calls to listPlaylistItems() are requesting the id instead of the snippet.
According to the documentation, the snippet costs 2 units of the API quota while requests for the id are 0. So, I don't need to snag the snippet for every single item on every single page. I only need to grab the snippet of the final video in the results, which I can do with the more refined call to
$youtube->videos->listVideos()
With the addition of the PlaylistCache class I only reach out to the API when the cached version of the Playlist returns true on the $playlistCache->isExpired() call, so I only need to poll the entire playlist one time every 24 hours instead of 1 time every page load for every user.
It's still not exactly ideal, but as far as I can tell, it's the best option available right now.
Firstly, you need to get the channelId for the user via HTTP request:
Sample request:
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername={0}&key={1}
where {0} is the USERNAME and key is you API key
Then, get the list of videos by calling 'PlaylistItems:list', it returns a collection of playlist items that match the API request parameters. You can retrieve all of the playlist items in a specified playlist or retrieve one or more playlist items by their unique IDs.
Sample request:
https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId={0}&key={1}
From there, you can create an array to get the last video in the playlist. Include max-results parameter, the max-results specifies the maximum number of results that included in the result set.
Typically, the latest video in a playlist in added to the front, not the end.
Does anyone know how to fetch all facebook ads statistics and display on webpage using Facebook Ads Api-PHP SDK. I am using this API and I am getting campaign details like name of campaign, id, status. but not able to get impressions,clicks, spent.
What I am doing let me share with you:
1) I am getting access token by authorizing user
2) After getting access token, I am using below code
$account = new AdAccount('act_XXXXXXXXXXXXXXX');
$account->read();
$fields = array(
AdCampaignFields::ID,
AdCampaignFields::NAME,
AdCampaignFields::OBJECTIVE,
);
$params = array(AdCampaignFields::STATUS => array(AdCampaign::STATUS_ACTIVE,AdCampaign::STATUS_PAUSED,),);
$campaigns = $account->getAdCampaigns($fields, $params);
/* Added By Jigar */
$campaign = new AdCampaign('XXXXXXXXXXXXXXXX');
$compainDetails = $campaign->read($fields);
3) then printing the array
echo "<pre>";
print_r($compainDetails);
exit;
If anyone know any suggestion in above code, please share. All code is in PHP. Dose anyone have any tutorial that fetch all above required data then share it
You could try to use the facebook insights api instead of $campaign->read. Here's an example:
https://developers.facebook.com/docs/marketing-api/insights/v2.5#create-async-jobs
What you have to do to get impressions, click and spent is to add these fields to the $fields param. In your case, the complete code should look like the following:
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Values\InsightsLevels;
use FacebookAds\Object\Values\InsightsFields;
$campaign = new Campaign();
$fields = array(
InsightsFields::IMPRESSIONS,
InsightsFields::UNIQUE_CLICKS,
InsightsFields::CALL_TO_ACTION_CLICKS,
InsightsFields::INLINE_LINK_CLICKS,
InsightsFields::SOCIAL_CLICKS,
InsightsFields::UNIQUE_SOCIAL_CLICKS,
InsightsFields::SPEND,
);
$params = array(
'level' => InsightsLevels::CAMPAIGN,
);
$async_job = $campaign->getInsightsAsync($fields, $params);
$async_job->read();
I don't know what exactly the "click" param means for you, but if you take a look at all these click params, I'm sure you'll find it or you'll know how to calculate it.
For a complete list of fields available on insights objects, have a look at: https://github.com/facebook/facebook-php-ads-sdk/blob/master/src/FacebookAds/Object/Fields/InsightsFields.php
Hope that helps.
Regards, Benjamin
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