remove videoid from youtube api output - php

Im using the youtube api to search for videos. My issue is that when a search is completed, the output from the search is
video_name video_id
I just want it to show
video_name
heres my code to display search results
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
$youtube = new Google_Service_YouTube($client);
try {
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
$videos = '';
$channels = '';
$playlists = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
$imgsrc="<img src=http://img.youtube.com/vi/".$searchResult['id']
['videoId']."/hqdefault.jpg height=125 width=125>";
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos .= sprintf('<li>'.$imgsrc.' %s (%s)</li>', $searchResult['snippet']['title'],
$searchResult['id']['videoId']."<a href=/video.php?".$searchResult['id']['videoId']." target=_blank> Watch This Video</a>");
break;

I'm not too familiar with sprintf but you want to remove
$searchResult['id']['videoId']
without breaking your code.
I'd suggest wrapping it in between a particular string e.g.
vidid[".$searchResult['id']['videoId']."]
and then remove all content between vidid[ and ].

Related

How to MODIFY a Google Docs document via API using search-and-replace?

I need an example of how to modify an existing document with existing text in Google Docs via API. The documentation only shows how to insert and delete text, but not how to update. Have been looking frantically on the web to find examples or a direction on how to do it but without luck.
Finally figured it out myself.
First, follow this video to prepare authentication to the Google Docs API (even though it's about Google Sheets but the process is basically the same). Basically it consists of these steps:
create project in Google Developer Console
enable Google Docs API
create credentials, including a service account for programmatic access
share your document with the service account client email address
install Google API's PHP client: composer require google/apiclient
Then create a script like the following:
require_once(__DIR__ .'/vendor/autoload.php');
$client = new \Google_Client();
$client->setApplicationName('Some name'); //this name doesn't matter
$client->setScopes([\Google_Service_Docs::DOCUMENTS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ .'/googleapi-credentials.json'); //see https://www.youtube.com/watch?v=iTZyuszEkxI for how to create this file
$service = new \Google_Service_Docs($client);
$documentId = 'YOUR-DOCUMENT-ID-GOES-HERE'; //set your document ID here, eg. "j4i1m57GDYthXKqlGce9WKs4tpiFvzl1FXKmNRsTAAlH"
$doc = $service->documents->get($documentId);
// Collect all pieces of text (see https://developers.google.com/docs/api/concepts/structure to understand the structure)
$allText = [];
foreach ($doc->body->content as $structuralElement) {
if ($structuralElement->paragraph) {
foreach ($structuralElement->paragraph->elements as $paragraphElement) {
if ($paragraphElement->textRun) {
$allText[] = $paragraphElement->textRun->content;
}
}
}
}
// Go through and create search/replace requests
$requests = $textsAlreadyDone = $forEasyCompare = [];
foreach ($allText as $currText) {
if (in_array($currText, $textsAlreadyDone, true)) {
// If two identical pieces of text are found only search-and-replace it once - no reason to do it multiple times
continue;
}
if (preg_match_all("/(.*?)(dogs)(.*?)/", $currText, $matches, PREG_SET_ORDER)) {
//NOTE: for simple static text searching you could of course just use strpos()
// - and then loop on $matches wouldn't be necessary, and str_replace() would be simplified
$modifiedText = $currText;
foreach ($matches as $match) {
$modifiedText = str_replace($match[0], $match[1] .'cats'. $match[3], $modifiedText);
}
$forEasyCompare[] = ['old' => $currText, 'new' => $modifiedText];
$replaceAllTextRequest = [
'replaceAllText' => [
'replaceText' => $modifiedText,
'containsText' => [
'text' => $currText,
'matchCase' => true,
],
],
];
$requests[] = new \Google_Service_Docs_Request($replaceAllTextRequest);
}
$textsAlreadyDone[] = $currText;
}
// you could dump out $forEasyCompare to see the changes that would be made
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
This is my way - easy one
public function replaceText($search, $replace)
{
$client = $this->getClient();
$service = new \Google_Service_Docs($client);
$documentId = ''; // Put your document ID here
$e = new \Google_Service_Docs_SubstringMatchCriteria();
$e->text = "{{".$search."}}";
$e->setMatchCase(false);
$requests[] = new \Google_Service_Docs_Request(array(
'replaceAllText' => array(
'replaceText' => $replace,
'containsText' => $e
),
));
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $requests
));
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
}

How to use optional parameters in Google Photos API?

I am working on project in php with Google Photos API. i have an issue, if i pass optional parameters like pageSize, it doesn't work still get all images.
$optParams = array(
'pageSize' => 1,
);
$response = $photosLibraryClient->listMediaItems($optParams);
foreach ($response->iterateAllElements() as $item) {
$id = $item->getId();
$description = $item->getDescription();
$mimeType = $item->getMimeType();
$productUrl = $item->getProductUrl();
$filename = $item->getFilename();
echo '<br>';
echo $filename;
}
I'm not a 100% sure of this, but it seems the iterateAllElements literally iterates over all elements available in the account, ignoring your specified pageSize (even the default pageSize) by requesting everything from the API without any boundaries.
You can iterate over the returned pages replacing iterateAllElements with iteratePages, but it also doesn't seems to work properly without a albumId, the API returns an irregular page sizing, like the example below:
$optParams = array(
'pageSize' => 5 // Changed
);
$response = $photosLibraryClient->searchMediaItems($optParams); // Changed the method
foreach ($response->iteratePages() as $key => $page) {
echo "Page #{$key}<br>";
foreach ($page as $item) {
$id = $item->getId();
$description = $item->getDescription();
$mimeType = $item->getMimeType();
$productUrl = $item->getProductUrl();
$filename = $item->getFilename();
echo '<br>';
echo $filename;
}
}
if the search or list were called without providing a albumId, the example above would return something like this:
[
[{...},{...},{...}],
[{...},{...},{...},{...},{...}],
[{...}],
[],
[{...},{...},{...},{...},{...}],
[]
]
If you find a good solution for this specific problem, please let me know.
Ps.: Their API behavior and it's documentation are very weird and confusing.

How can I update a YouTube Video? | PHP

I try update a YouTube Video. I use the function at the site https://developers.google.com/youtube/v3/code_samples/php#update_a_video and I try to copy this in my code but if I call listVideos(), I get Google_Service_YouTube_VideoListResponse but I need a Google_Service_YouTube_Video. How can I get it?
My PHP Code:
$youtube = new Google_Service_YouTube($client);
$videoid = "******Video ID********";
$new = "******* TEXT *********";
$videoinfo = $youtube->videos->listVideos('snippet', array('id' => $videoid));
$videoSnippet = $videoinfo[0]['snippet'];
$description = $videoSnippet['description'] . $new;
$videoSnippet['description'] = $description;
$youtube->videos->update("snippet", $videoSnippet);
The Error:
: Uncaught TypeError: Argument 2 passed to
Google_Service_YouTube_Resource_Videos::update() must be an instance of
Google_Service_YouTube_Video, instance of
Google_Service_YouTube_VideoSnippet given, called in
P:\Apache24\htdocs\*********** on line 232 and defined in
P:\Apache24\htdocs\*******\Google Api System\vendor\google\apiclient-
services\src\Google\Service\YouTube\Resource\Videos.php:309
Stack trace:
0 P:\Apache24\htdocs\*********: Google_Service_YouTube_Resource_Videos-
>update('snippet', Object(Google_Service_YouTube_VideoSnippet ))
1 P:\Apache24\htdocs\********\*********\index.php(438):
require('P:\\Apache24\\htd...')
you have to use
$video = $listResponse[0];
$updateResponse = $youtube->videos->update("snippet", $video);
since in the documentation
// Since the request specified a video ID, the response only
// contains one video resource.
$video = $listResponse[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// Preserve any tags already associated with the video. If the video does
// not have any tags, create a new list. Replace the values "tag1" and
// "tag2" with the new tags you want to associate with the video.
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Set the tags array for the video snippet
$videoSnippet['tags'] = $tags;
// Update the video resource by calling the videos.update() method.
$updateResponse = $youtube->videos->update("snippet", $video);

PHP - How to get tweet count, following count, follower count and like count from Twitter REST api?

I have the following code to request follower count from twitter api.
<?php
/*
* Requires the "Twitter API" wrapper by James Mallison
* to be found at https://github.com/J7mbo/twitter-api-php
*
* The way how to get a follower count was posted by Amal Murali
* on http://stackoverflow.com/questions/17409227/follower-count-number-in-twitter
*/
require_once('twitterapi/TwitterAPIExchange.php'); // adjust server path accordingly
// GET YOUR TOKENS AND KEYS at https://dev.twitter.com/apps/
$settings = array(
'oauth_access_token' => "SECRET", // enter your data here
'oauth_access_token_secret' => "SECRET", // enter your data here
'consumer_key' => "SECRET", // enter your data here
'consumer_secret' => "SECRET" // enter your data here
);
$ta_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=SECRET'; // enter your twitter name without the "#" here
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
->buildOauth($ta_url, $requestMethod)
->performRequest();
$data = json_decode($follow_count, true);
$followers_count = $data[0]['user']['followers_count'];
?>
It is working perfectly, but it only gets the follower count. I would also like the tweet count, following count, and like count.
According to the twitter api documentation the ones I need are all available from https://api.twitter.com/1.1/statuses/user_timeline.json. They are called:
Tweets = "statuses_count", Following = "friends_count", Likes = "favourites_count"
Problem is I can't work out how to adapt the code to call for all 4 variables. I did try just repeating the GET request and changing the variable names but it didn't seem to work.
Any help would be greatly appreciated!
UPDATE:
A big thank you to OldPadawan, his code worked perfectly.
This is what the final code looks like:
<?php
/*
* Requires the "Twitter API" wrapper by James Mallison
* to be found at https://github.com/J7mbo/twitter-api-php
*
* The way how to get a follower count was posted by Amal Murali
* on http://stackoverflow.com/questions/17409227/follower-count-number-in-twitter
*/
require_once('twitterapi/TwitterAPIExchange.php'); // adjust server path accordingly
// GET YOUR TOKENS AND KEYS at https://dev.twitter.com/apps/
$settings = array(
'oauth_access_token' => "xxxxx", // enter your data here
'oauth_access_token_secret' => "xxxxx", // enter your data here
'consumer_key' => "Xxxxx", // enter your data here
'consumer_secret' => "xxxxx" // enter your data here
);
$ta_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=ConsoleRepairHQ'; // enter your twitter name without the "#" here
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
->buildOauth($ta_url, $requestMethod)
->performRequest();
$data = json_decode($follow_count, true);
foreach($data as $tweets) { // we run through the array
$followers = $tweets['user']['followers_count'];
$friends = $tweets['user']['friends_count'];
$likes = $tweets['user']['favourites_count'];
$statuses = $tweets['user']['statuses_count'];
} // end of loop
?>
Once you get the json response from Twitter, you treat it as an array and use foreach
see example of a response array from Twitter Dev Doc
see PHP Doc foreach
In your case, after :
$data = json_decode($follow_count, true);
You can print the array to see what it looks like (just for information, not needed later) but it makes it easier to understand the logic and where data is stored (can be different array structure)
What you need, is to add this :
<?php
$data = json_decode($follow_count, true);
print_r($data); // just checking, not needed later
foreach($data as $tweets) { // we run through the array
// here's an example of the structure and how you access it
// compare to the printed array if you need more information
$tweet = $tweets['text'];
$name = $tweets['user']['name'];
$turl = $tweets['user']['url'];
$followers = $tweets['user']['followers_count'];
$friends = $tweets['user']['friends_count'];
$likes = $tweets['user']['favourites_count'];
echo "Tweet: $tweet ($name / $turl) -> followed by : $followers -> friends: $friends -> likes: $likes<br />";
} // end of loop
?>
And you're done. Hope this helps :)

Google Youtube API watch later

I would like to get all my youtube watch later video list whith PHP API 3.0 but it seem's that we can not access to these with PHP and API 3. Does anyone have done it yet ?
My code for now
// Call the YouTube Data API's channelSections.list method to retrieve your channel sections.
$listResponse = $youtube->channelSections->listChannelSections('snippet,contentDetails', array('mine' => true));
$channelSections = $listResponse['items'];
$htmlBody .= "<h2>Sections Shuffled</h2><ul>";
foreach ($channelSections as $channelSection) {
// Each section in the list of shuffled sections is sequentially
// set to position 0, i.e. the top.
$channelSection['snippet']['position'] = 0;
// Call the YouTube Data API's channelSections.update method to update a channel section.
$updateResponse = $youtube->channelSections->update('snippet,contentDetails', $channelSection);
$htmlBody .= sprintf('<li>%s "%s"</li>',
$updateResponse['id'], $updateResponse['snippet']['title']);
}
$htmlBody .= '</ul>';
Use $youtube->channels->listChannels instead of $youtube->channelSections->listChannelSections
// Get all channels of current user
$channels = $youtube->channels->listChannels('contentDetails', ['mine' => true]);
// Get watch later playlists ID from the first channel
$watchLaterListId = $channels[0]->getContentDetails()->getRelatedPlaylists()->getWatchLater();
// Get videos from the playlist
$videos = $youtube->playlistItems->listPlaylistItems('contentDetails', ['playlistId' => $watchLaterListId]);
// Loop videos
foreach($videos as $video)
{
// This is the global video ID.
$globalVideoId = $video->getContentDetails()->getVideoId();
// This is unique ID of this video on the playlist. The one you need to interact with the playlist
$playlistVideoId = $video->id;
//i.e: To remove this video from the playlist
$youtube->playlistItems->delete($playlistVideoId);
}

Categories