I'm a beginner at PHP. I have one task in my project, which is to fetch all videos from a YouTube link using curl in PHP. Is it possible to show all videos from YouTube?
I found this code with a Google search:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.youtube.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
echo $contents;
curl_close ($ch);
?>
It shows the YouTube site, but when I click any video it will not play.
You can get data from youtube oemebed interface in two formats Xml and Json which returns metadata about a video:
http://www.youtube.com/oembed?url={videoUrlHere}&format=json
Using your example, a call to:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json
So, You can do like this:
$url = "Your_Youtube_video_link";
Example :
$url = "http://www.youtube.com/watch?v=m7svJHmgJqs"
$youtube = "http://www.youtube.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo $result['html'];
Try it...Hope it will help you.
You could use curl to retrieve the Google main page (or an alternative page) and parse the returned html using a library such as html5lib. If you wanted to try this approach the first step could be to 'view source' on the relevant page and look at how the links are structured.
A more elegant way to approach the problem could be to use the Youtube API (a way to interact with the Youtube system), which may allow you to retrieve the links directly. e.g it may be possible to just ask the Youtube API to send you the links. Try this.
You can also get all youtube's channel videos using file_get_contents
bellow is sample and working code
<?php
$Youtube_API_Key = ""; // you can obtain api key : https://developers.google.com/youtube/registering_an_application
$Youtube_channel_id = "";
$TotalVideso = 50; // 50 is max , if you want more video you need Youtube secret key.
$order= "date"; ////allowed order : date,rating,relevance,title,videocount,viewcount
$url = "https://www.googleapis.com/youtube/v3/search?key=".$Youtube_API_Key."&channelId=".$Youtube_channel_id."&part=id&order=".$order."&maxResults=".$TotalVideso."&format=json";
$data = file_get_contents($url);
$JsonDecodeData=json_decode($data, true);
print_r($data);
?>
Related
I have problem when I want to fetch image that was sent to my DM.
So when I fetch the DM data from API, I got the media id for the image but how to fetch it?
I want to fetch the image and tweet it to my account.
So basically:
Someone send DM to me with media
I read my account DM from API
Tweet DM content to my account
Here is my code
$AMConnection = new \Twitter\OAuth(AM_CONSUMER_KEY, AM_CONSUMER_SECRET);
$AMConnection->setAccessToken($amService->token, $amService->secret);
$jsonData = json_decode(file_get_contents("./fetchDM.json"));
foreach ($jsonData as $json) {
if (!isset($json->entities->media)) continue;
$medias = $json->entities->media;
$postParam['status'] = $json->text;
foreach ($medias as $image) {
$postParam['status'] = str_replace($image->url, "", $postParam['status']);
$postParam['media_ids'][] = $image->id_str;
}
echo "SEND TWEET".PHP_EOL;
$return = $AMConnection->post('statuses/update', $postParam);
var_dump($return);
if (isset($return->errors) and count($return->errors) > 0) {
foreach ($return->errors as $error) {
if ($error->code == 89) {
$amService->token = null;
$amService->secret = null;
$amService->save();
break;
}
}
}
}
On my code, I was tried to tweet media using media_id but it doesn't work.
Sorry for bad english
Finally it's solved.
So I've been look for this one on some forums but only 2 forum has answer, 1 on twitter forum (sorry I don't have link) and another 1 StackOverflow
I'm using library and try messing out with it but deadend. The library that I've used to request REST API, use OAuth request from URL and POST data. Yeah, it's totally work (only for REST API) but this one is totally different.
To fetch image from DM, YOU MUST REQUEST USING HEADER AUTHORIZATION and no other way.
On my sample, I want to try to fetch https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg (This one is image url from DM, so only me and someone who've sent me that image only can see it).
I'm using CURL PHP to fetch the image so the request will be like this
<?php
$this->http_info = array();
$ci = curl_init();
$url = 'https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg';
$headerAuth = 'Authorization: OAuth oauth_version="1.0",
oauth_nonce="{autoGeneratedNonce}",
oauth_timestamp="{time()}",
oauth_consumer_key="{yourAppToken}",
oauth_token="{userToken}",
oauth_signature_method="HMAC-SHA1",
oauth_signature="{autoGeneratedSignature}"';
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, 'LShaf User Agent');
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, [$headerAuth]);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_HEADER, FALSE);
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
curl_close ($ci);
Note: You MUST use method GET and put Authorization on HEADER.
And for the last thing, I'm sorry for my bad english.
I have created a class managing the connection to Google Contacts API, authenticate and return the contacts.
I've successfully got the contacts list, But I didn't yet manage to get the contact photo. This is my html code :
<img src="<?= $service->getPhoto($contact['image']) ?>" />
and this is my php:
public function getPhoto($url = false){
if(!$url)
return false;
$url = urlencode($url.'&access_token='.$this->_access_token);
//echo $url.'&access_token='.$this->_access_token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
$image = curl_exec($curl);
curl_close($curl);
return $image;
}
Note that the $url argument is the url provided by the contacts data returned by the Google API, it's like as the following:
https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactID}
This is an exemple of an URL (according to my project) :
https://www.google.com/m8/feeds/photos/media/example%40gmail.com/ABCDEFGHIJK2345
Sometimes the contactId contains a '/'
The error message from Google is :
401. That's an error.
There was an error in your request. That's all we know.
Did I miss something?
NOTE: I tried with urlencode, urldecode and tried without using them...But I got the same problem. Also, the contacts I'm testing with have gmail photos.
You are encoding your whole url and probably which is causing the mess!?
$url = $url . '&access_token=' . urlencode($this->_access_token);
I've finally solved the problem, and this is what I did:
I changed the '&' to '?' in the $url
$url.'&access_token='.$this->_access_token
changed to :
$url.'?access_token='.$this->_access_token
Since access_token is the first parameter ... and I removed the curl, I just returned the $url as it is and put it in the image src.
Although it's somehow solved, I don't know if it's okey to put the access_token in the src of the image (which can be viewed by any client side user).
I am learning the instagram api to fetch certain hashtag image into my website recently.
After searching on the webs for a very long time I coundnt find any workable code for it.
Anyone can help?
Thanks!
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
You will need to use the API endpoint for getting a list of recently tagged media by the hashtag. It would look something like this to get media for the hashtag #superpickle
https://api.instagram.com/v1/tags/superpickle/media/recent
You will need to read the Instagram API documentation to learn more about it and how to register for a client ID. http://instagram.com/developer/
You can use statigram cURL method, isnt Instagram API, but can resolve it.
Im use CodeIgniter and make a service to return a XML, usign simple_xml_load to read feed.
Good Lucky.
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, "http://statigr.am/feed/cristiano");
$content = curl_exec($curl);
curl_close($curl);
$this->xml = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
echo json_encode($this->xml->channel);
Search on Google images with car keyword & get car images.
I found two links to implement like this,
PHP class to retrieve multiple images from Google using curl multi
handler
Google image API using cURL
implement also but it gave 4 random images not more than that.
Question: How to get car images in PHP using keyword i want to implement like we search on Google?
Any suggestion will be appreciated!!!
You could use the PHP Simple HTML DOM library for this:
<?php
include "simple_html_dom.php";
$search_query = "ENTER YOUR SEARCH QUERY HERE";
$search_query = urlencode( $search_query );
$html = file_get_html( "https://www.google.com/search?q=$search_query&tbm=isch" );
$image_container = $html->find('div#rcnt', 0);
$images = $image_container->find('img');
$image_count = 10; //Enter the amount of images to be shown
$i = 0;
foreach($images as $image){
if($i == $image_count) break;
$i++;
// DO with the image whatever you want here (the image element is '$image'):
echo $image;
}
This will print a specific number of images (number is set in '$image_count').
For more information on the PHP Simple HTML DOM library click here.
i am not very much sure about this ,but still google gives a nice documentation about this.
$url = "https://ajax.googleapis.com/ajax/services/search/images?" .
"v=1.0&q=barack%20obama&userip=INSERT-USER-IP";
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */);
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...
this is from the official Google's developer guide regarding image searching.
for more reference you can have a reference of the same here.
https://developers.google.com/image-search/v1/jsondevguide#json_snippets_php
in $url you must set the search keywords.
I would like to know how is it possible to retrieve a string from an external page.
For example: In a PHP website, the user sends a facebook id, ex: 1157251270
And the website returns the name from http://graph.facebook.com/1157251270.
I hope I made it clear.
Thank you
The Graph API returns JSON strings, so you can use:
echo json_decode(file_get_contents('http://graph.facebook.com/1157251270'))->name;
or more verbose:
$pageContent = file_get_contents('http://graph.facebook.com/1157251270');
$parsedJson = json_decode($pageContent);
echo $parsedJson->name; // Romanos Fessas
See json_decode — Decodes a JSON string
If you are using Facebook's PHP SDK, you can also do this to query their graph API:
$fb = new Facebook();
$object = $fb->api('/1157251270');
you get it by:
$link = json_decode(file_get_contents('http://graph.facebook.com/1157251270'));
echo $link->name;
Nice tut:
http://webhole.net/2009/08/31/how-to-read-json-data-with-php/
Either you use :
$res_json = file_gets_contents("http://graph.facebook.com/1157251270")
$res = json_decode($res_json)
Or, if you prefer curl (here with https and access token) :
$ch4 = curl_init();
curl_setopt($ch4, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch4, CURLOPT_URL, "https://graph.facebook.com/1157251270?access_token=YOUR_ACCESS_TOKEN");
curl_setopt($ch4, CURLOPT_SSL_VERIFYPEER, false);
if(!$result = curl_exec($ch4))
{
echo curl_error($ch4);
} else {
$res = json_decode($res_json)
}
curl_close($ch4);
For facebook data you can use json_decode.
For another sites try with webscraping, for example:
here