Youtube get video title from id - php

I understand this may have been answered somewhere, but after looking and looking through numerous questions/answers and other websites, I'm unable to find a suitable answer.
I'm trying to create a page, which will show some video from Youtube. It will show the image, and title. I've managed to do both of these, although i'm having problems with the title. With the code i'm using, it is awfully slow at loading. I assume because of it loading the actual website just to get the title.
This is what i'm using to get the titles currently.
function get_youtube_id($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);
$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;
return $title;
}
So, how would the best way to get a youtube title by the id. The code I have does work, but it also makes the page load very very slow.
Thanks

Here is a simple way to do it using PHP and no library. YouTube already allows you to retrieve video detail information in the JSON format, so all you need is a simple function like this:
function get_youtube_title($ref) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$details = json_decode($json, true); //parse the JSON into an array
return $details['title']; //return the video title
}
The function parameter being the video ID. You could also add a second parameter asking for a specific detail and change the function name so you could retrieve any data from the JSON that you would like.
EDIT:
If you would like to retrieve any piece of information from the returned video details you could use this function:
function get_youtube_details($ref, $detail) {
if (!isset($GLOBALS['youtube_details'][$ref])) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
}
return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}
If you request different details about the same video, the returned JSON data is stored in the $GLOBALS array to prevent necessary calls to file_get_contents.
Also, allow_url_fopen will have to be on in your php.ini for file_get_contents to work, which may be a problem on shared hosts.

You can use Open Graph
Checkout This Link
<?php
require_once('OpenGraph.php');
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$graph = OpenGraph::fetch($url);
// You can get title from array
return $graph->title;
}

It's been 5 years, but my script bellow could be useful.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/watch?v=YOUTUBEID");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$document = htmlspecialchars($output);
curl_close($ch);
$line = explode("\n", $document);
$judul = "";
foreach($line as $strline){
preg_match('/\<title\>(.*?)\<\/title\>/s', $strline, $hasil);
if (!isset($hasil[0]) || $hasil[0] == "") continue;
$title = str_replace(array("<title>", "</title>"), "", $hasil[0]);
}
echo $title;

Related

Get vine image with cURL

Im trying to get vine image using cURL but its returning empty.
I want to extract the image from vine meta tags
<meta property="twitter:image:src" content="https://v.cdn.vine.co/r/thumbs/C40D8A18E21388329752896937984_58406422053.35.0.D4119957-7F82-4C6F-94EC-4732C58E79E1.mp4.jpg?versionId=lWIZyat1QyiI8rjnz3KFsbWtuOoUmGFn">`
This is my code
$ch1eckUrl = "https://vine.co/v/51wPzgnEHLb";
function getVineVideoFromImage($ch1eckUrl) {
$ch1 = curl_init($ch1eckUrl);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$res1 = curl_exec($ch1);
preg_match('/twitter:image:src.*content="(.*)"/', $res1, $opimage);
$VineImage = $opimage[1];
}
Applicate if someone can point me what im doing wrong here
The Answer is already posted here:How to get Vine video url
You've even copied an answer. Just replace twitter:player:stream. with twitter:image:src.
My bad, didn't read Image
On that note, there's an even easier way:
<?php
$ch1eckUrl = 'https://vine.co/oembed/51wPzgnEHLb.json';
function getVineVideoFromImage($ch1eckUrl) {
$json = json_decode(file_get_contents($ch1eckUrl), true);
return $json['thumbnail_url'];
}
$VineImage = getVineVideoFromImage($ch1eckUrl);
echo($VineImage);
?>
Vine servers JSON, so just fetch that and decode it and you got the url.

We are creating an application like news feed.How to get data from rss feeds and i need to provide webservice through json

We are creating an application like news feed.How to get data from rss feeds and i need to provide webservice through json.I am using php codeigniter as server side scripting.
How to get feeds from different sites and send json response dynamically.
There's quite a lot of rss feed jquery plugins out there. That could be a simple and fast to implement solution for a basic need.
For example see zrrsfeed (Check the examples).
That's just one rss plugins among many others.
An Alternative to jquery could be php CURL, and an example of printing out the feed onto the screen from curl could happen 1 of two ways, from an RSS source, or as an ATOM source, this of course depends on the source FEED.
More Information about Atom vs RSS can be found here:
https://shafiq2410.wordpress.com/2012/08/05/rss-vs-atom-which-one-is-better/
An Example of integrating BOTH into 1 application could look like this
// RSS
function parseRSS($xml)
{
echo "<strong>".$xml->channel->title."</strong><br />";
$cnt = count($xml->channel->item);
for($i=0; $i<$cnt; $i++)
{
$url = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$desc = $xml->channel->item[$i]->description;
echo ''.$title.''.$desc.'<br />';
}
}
// Atom
function parseAtom($xml)
{
echo "<strong>".$xml->author->name."</strong><br />";
$cnt = count($xml->entry);
for($i=0; $i<$cnt; $i++)
{
$urlAtt = $xml->entry->link[$i]->attributes();
$url = $urlAtt['href'];
$title = $xml->entry->title;
$desc = strip_tags($xml->entry->content);
echo ''.$title.''.$desc.'<br />';
}
}
$ch = curl_init("http://domain.com/path/to/rss.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);
if(isset($doc->channel))
{
// Parse as RSS
parseRSS($doc);
}
if(isset($doc->entry))
{
// Parse as ATOM
parseAtom($doc);
}
Of course instead of echoing out the results, you could handle them however you needed at this point, being that i dont know your overall goal here, i wanted to at least point you in the CURL direction as an option.
I hope this helps get you started.

Change Output of PHP Script to use POST Method

Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>
Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);

Get Google Search Images using php

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.

PHP Scraper appears to be in an infinite loop

(I'm scraping this stuff with the permission of the website in question, by the way).
Pretty simple web scraper, was working fine when I was loading all the links by hand, but when I've tried to load them in via JSON and variables (so I can do lots of scraping with the one script and make the process more modular by just adding more links to JSON) it runs on an infinite loop.
(Page has been loading for about 15 minutes now)
Here is my JSON. Only one store is in there for testing purposes but there is going to be about 15 more.
[
{
"store":"Incu Men",
"cat":"Accessories",
"general_cat":"Accessories",
"spec_cat":"accessories",
"url":"http://www.incuclothing.com/shop-men/accessories/",
"baseurl":"http://www.incuclothing.com",
"next_select":"a.next",
"prod_name_select":".infobox .fn",
"label_name_select":".infobox .brand",
"desc_select":".infobox .description",
"price_select":"#price",
"mainImg_select":"",
"more_imgs":".product-images",
"product_url":".hproduct .photo-link"
}
]
Here is the PHP scraper code:
<?php
//Set infinite time limit
set_time_limit (0);
// Include simple html dom
include('simple_html_dom.php');
// Defining the basic cURL function
function curl($url) {
$ch = curl_init();
// Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url);
// Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Setting cURL's option to return the webpage data
$data = curl_exec($ch);
// Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch);
// Closing cURL
return $data;
// Returning the data from the function
}
function getLinks($catURL, $prodURL, $baseURL, $next_select) {
$urls = array();
while($catURL) {
echo "Indexing: $url" . PHP_EOL;
$html = str_get_html(curl($catURL));
foreach ($html->find($prodURL) as $el) {
$urls[] = $baseURL . $el->href;
}
$next = $html->find($next_select, 0);
$url = $next ? $baseURL . $next->href : null;
echo "Results: $next" . PHP_EOL;
}
return $urls;
}
$string = file_get_contents("jsonWorkers/incuMens.json");
$json_array = json_decode($string,true);
foreach ($json_array as $value){
$baseURL = $value['baseurl'];
$catURL = $value['url'];
$store = $value['store'];
$general_cat = $value['general_cat'];
$spec_cat = $value['spec_cat'];
$next_select = $value['next_select'];
$prod_name = $value['prod_name_select'];
$label_name = $value['label_name_select'];
$description = $value['desc_select'];
$price = $value['price_select'];
$prodURL = $value['product_url'];
if (!is_null($value['mainImg_select'])){
$mainImg = $value['mainImg_select'];
}
$more_imgs = $value['more_imgs'];
$allLinks = getLinks($catURL, $prodURL, $baseURL, $next_select);
}
?>
Any ideas why the script would be running infinitely and not returning anything/stopping/printing anything to screen? I'm just gonna let it run until it stops. When I was doing this by hand it would only take a minute or so, sometimes less, so I'm sure it's a problem with my variables/json but I can't for the life of me see what the issues lie.
Can anyone take a quick look and point me in the right direction?
There is a problem with your while($catURL) loop. What do you want to do ?
Moreover, you can force to display information on your browser with the flush() command.

Categories