2013-09-02 4 views
0

Я адаптировал код от youtube getting Meta-data of a video, чтобы иметь возможность печатать метаданные. Он отлично работает, за исключением того, что окончательная строка не печатает заголовок.

$url = ("PUT A YOUTUBE URL HERE"]); 
$youtube = "http://www.youtube.com/oembed?url=".$url."&format=json"; 
$json = file_get_contents($youtube); 

printf('<br />vid_code is %s', $row["vid_code"]); 
printf('<br />vid_url is %s', $row["vid_url"]); 
printf('<br />$url is %s', $url); 
printf('<br />$youtube is %s', $youtube); 
printf('<br />$json is %s', $json); 
printf ('<br />Title is: '.$json->title); //THIS IS THE LINE THAT IS NOT WORKING 

Кажется довольно простым ... чего я не хватает?

+0

игнорировать] в строке $ url .... typo – fluxcapacitor

ответ

0

Вы забыли декодировать JSON, использовать json_decode()

Вот пример:

<?php 
$url = "http://www.youtube.com/watch?v=-iMR0uac2Kg"; 
$youtube = "http://www.youtube.com/oembed?url=".urlencode($url)."&format=json"; 
$json = json_decode(file_get_contents($youtube)); 

echo '<pre>'.print_r($json,true).'</pre>'; 
/* 
stdClass Object 
(
    [author_name] => Haim Michael 
    [version] => 1.0 
    [width] => 480 
    [type] => video 
    [provider_url] => http://www.youtube.com/ 
    [height] => 270 
    [author_url] => http://www.youtube.com/user/lifemichael 
    [provider_name] => YouTube 
    [thumbnail_width] => 480 
    [thumbnail_height] => 360 
    [html] => <iframe width="480" height="270" src="http://www.youtube.com/embed/-iMR0uac2Kg?feature=oembed" frameborder="0" allowfullscreen></iframe> 
    [title] => The json_decode Function in PHP 
    [thumbnail_url] => http://i1.ytimg.com/vi/-iMR0uac2Kg/hqdefault.jpg 
) 
*/ 

//So to get the title: 
echo $json->title; 
?> 
1

Я не могу полностью признать подход ->https://developers.google.com/youtube/2.0/developers_guide_json

Я бы сделать что-то вроде:

$url = "OINa46HeWg8"; //some random video 
$youtube = 'http://gdata.youtube.com/feeds/api/videos/'.$url.'?v=2&alt=jsonc'; 
$json = file_get_contents($youtube); 

$json = json_decode($json, true); 
$title = $json['data']['title']; 
echo $title; 

Выходы:

I Forgot My Phone 

HTML:

<h1><? echo $title;?></h1> 
<iframe width="420" height="315" src="//www.youtube.com/embed/<? echo $url;?>" frameborder="0" allowfullscreen></iframe> 

Намного проще, и нет накладных расходов.

Смежные вопросы