通过PHP

时间:2015-10-13 19:14:18

标签: php video youtube-api

首先,这不是重复的问题 StackOverflow关于YouTube API的其他答案是2013年之前的,不再有效。

我必须使用PHP中的YouTube视频ID获取YouTube视频标题。

目前我这样做:

    $html = "http://www.youtube.com/watch?v=".$video_id;
    $doc = new DOMDocument();
    $doc->loadHTMLFile($html);
    $doc->preserveWhiteSpace = false;
    $title_div = $doc->getElementById('eow-title');
    $title = $title_div->nodeValue;

但这会引发错误:

Warning: DOMDocument::loadHTMLFile(http://www.youtube.com/watch?v=hMpCsfvi_3c): failed to open stream: HTTP request failed! HTTP/1.0 429 Too Many Requests in /home/vhosts/xxxx/xxxx/get_youtube_title.php on line 6

Warning: DOMDocument::loadHTMLFile(): I/O warning : failed to load external entity "http://www.youtube.com/watch?v=hMpCsfvi_3c" in /home/vhosts/xxxx/xxxx/get_youtube_title.php on line 6

上述方法适用于Godaddy托管,但不适用于101domain.com托管。

我尝试的另一种方法是:

if($content=file_get_contents("http://youtube.com/get_video_info?video_id=".$video_id)) {
    parse_str($content, $ytarr);
    $myvideos[$i]['video_title']=$ytarr['title'];
}
else
$myvideos[$i]['video_title']="No title";

这会抛出错误:

Warning: DOMDocument::loadHTMLFile(http://youtube.com/get_video_info?video_id=hMpCsfvi_3c): failed to open stream: HTTP request failed! HTTP/1.0 402 Payment Required in /home/vhosts/xxxx/get_youtube_title.php on line 6

Warning: DOMDocument::loadHTMLFile(): I/O warning : failed to load external entity "http://youtube.com/get_video_info?video_id=hMpCsfvi_3c" in /home/vhosts/xxxx/get_youtube_title.php on line 6

我尝试的最后一种方法是:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://youtube.com/get_video_info? video_id=".$video_id);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

这不会引发任何错误,但也不起作用。 错误报告为E_ALLdisplay_errors设置为1。

有人告诉我使用YouTube API更安全,因为我是YouTube新手,我需要一些帮助。

请告诉我如何在PHP中获取带有视频ID的视频标题? 也是一个易于理解的YouTube API教程。

8 个答案:

答案 0 :(得分:6)

我使用了file_get_contents(),但这次我使用了不同的网址。

我使用的网址是:

https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key='.$YoutubeAPIKey.'&part=snippet

例如:

function get_youtube_title($video_id){
    $html = 'https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key=alskdfhwueoriwaksjdfnzxcvxzfserwesfasdfs&part=snippet';
    $response = file_get_contents($html);
    $decoded = json_decode($response, true);
    foreach ($decoded['items'] as $items) {
         $title= $items['snippet']['title'];
         return $title;
    }
}
echo $title = get_youtube_title('PQqudiUdGuo');

答案 1 :(得分:3)

这对我有用:

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "rg"))
public class Usuario implements AbstractEntity{

@Id
@GeneratedValue
private Long id;

@NotNull
@Size(min = 1, max = 150)
@Pattern(regexp = "[^0-9]*", message = "Não deve conter números")
private String nome;

@NotNull
private String cpfCnpj;

@NotNull
private String rg;

@Temporal(TemporalType.DATE)
private Date dataNascimento;

@OneToOne(cascade = CascadeType.ALL)
private Contato contato;

@OneToOne(cascade = CascadeType.ALL)
private Endereco endereco;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "usuario_id")
private List<Login> login;

@Enumerated
private TipoPessoa tipoPessoa;

@Enumerated
private TipoPrevilegio previlegio;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "usuario_id")
private List<Cobranca> cobranca;

// GETTERS E SETTERS

public void setLogin(List<Login> login) {
    this.login = login;
}

public void addLogin(Login login){
    if(this.login == null)
        this.login = new ArrayList<Login>();
    this.login.add(login);
}

public void addLogin(){
    this.addLogin(new Login(this)); 
}

public void removeLogin(Login login){
    if(this.login.contains(login))
        this.login.remove(login);
}
}

这也有效(这与你的第一种方法完全相同):

<ui:composition xmlns="http://www.w3.org/1999/xhtml"  
            xmlns:h="http://java.sun.com/jsf/html"  
            xmlns:f="http://java.sun.com/jsf/core"  
            xmlns:ui="http://java.sun.com/jsf/facelets"
            xmlns:p="http://primefaces.org/ui" 
            template="WEB-INF/templates/default/main.xhtml"
            xmlns:b="http://bootsfaces.net/ui">
<ui:define name="content">                        
    <h1 class="page-header "> <i class="fa fa-tachometer"></i> Dashboard</h1>
    <ol class="breadcrumb">
        <li class="active">Inicio</li>
    </ol>
    <h:form>
    <b:messages styleClass="messages"
           errorClass="invalid" infoClass="valid"
           warnClass="warning" globalOnly="true"/>
    <h:panelGrid columns="3" columnClasses="titleCell">
           <h:dataTable id="tabelaLogin" value="#{testController.usuario.login}" var="l"
              styleClass="table table-striped table-bordered">
              <h:column>
                 <!-- column header -->
                 <f:facet name="header">Usuário</f:facet>
                 <!-- row record -->
                 <b:inputText id="user" value="#{l.user}" />
              </h:column>
              <h:column>
                 <f:facet name="header">Senha</f:facet>
                 <b:inputText id="pass" value="#{l.pass}" />
              </h:column>
              <h:column>
                 <f:facet name="header">MAC</f:facet>
                 <b:inputText id="mac" value="#{l.mac}" />
              </h:column>
              <h:column>
                 <f:facet name="header">Plano</f:facet>
                 <b:selectOneMenu id="plano" name="plano" value="#{l.plano}" converter="planoConverter">
                    <f:selectItems value="#{planoController.findAll()}" var="pl" itemLabel="#{pl.nome}" itemValue="#{pl}"/>
                 </b:selectOneMenu>
                 <h:message for="plano" errorClass="invalid" />
              </h:column>
              <h:column>
                 <f:facet name="header">#</f:facet>
                 <b:commandButton action="#{testController.usuario.removeLogin(l)}" value="Apagar" look="danger" />
              </h:column>
           </h:dataTable>
           <b:commandButton value="Add Login" actionListener="#{testController.usuario.addLogin()}"  update="tabelaLogin" look="success" />
           <b:commandButton value="Salvar" actionListener="#{testController.salvar()}"  update="tabelaLogin" look="success" />
        </h:panelGrid>
        </h:form>
</ui:define>

因此,我认为您的问题与您的代码之外的其他问题有关。

答案 2 :(得分:3)

这是我创建的单行代码:

echo explode('</title>', explode('<title>', file_get_contents("https://www.youtube.com/watch?v=VideoIDHERE"))[1])[0];

答案 3 :(得分:1)

使用Youtube API v3和以id身份发送的列表方法作为参数,您将获得有关该特定视频的信息https://developers.google.com/youtube/v3/docs/videos/list#id

  

获取https://www.googleapis.com/youtube/v3/videos

使用id参数

  

的字符串   id参数指定要检索的资源的YouTube视频ID的逗号分隔列表。在视频资源中,id属性指定视频的ID。

在使用php sdk的情况下,示例将类似于

# Call the videos.list method to retrieve location details for each video.
$videosResponse = $youtube->videos->listVideos('snippet, recordingDetails', array(
'id' => $videoIds,
));

答案 4 :(得分:1)

function get_youtube($url){

    $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);
    return json_decode($return, true);
}

$url = // youtube video url 
// Display Data 
print_r(get_youtube($url));

答案 5 :(得分:1)

$video_info = file_get_contents('https://www.youtube.com/get_video_info?video_id=' . $video_id);
parse_str($video_info, $video_info_array);
$title = json_decode($video_info_array['player_response'])->videoDetails->title;

答案 6 :(得分:0)

我尝试了以前没有php sdk的解决方案,但它们对我不起作用。如果尝试使用file_get_contents,我会从API中收到错误消息。
我检查了YouTube API v3,目前(2019年)该解决方案对我有效。 您需要从Google Cloud Platform获得自己的YouTube API密钥(或全局API密钥)。在示例中替换“ yourAPIkey”后:

function get_youtube_title($video_id){
  $url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id='.$video_id.'&key=yourAPIkey';
  $curl = curl_init($url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $data = curl_exec($curl);
  curl_close($curl);
  $decoded = json_decode($data, true);
  foreach ($decoded['items'] as $items) {
     $title= $items['snippet']['title'];
     return $title;
  }
}
echo $title = get_youtube_title('fhntQrZsjdw');

如果您从https发送请求,则可以使用。在http或不安全的本地主机中,将放在curl_exec之前多一行:

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

答案 7 :(得分:-1)

PHP代码段

function getTubeTitel($id)
{
    $tmp = file_get_contents("http://youtube.com/watch?v=" . $id);

    $tmp2 = substr($tmp, (strpos($tmp, "<title>") + 7), 220);

    $tmp = substr($tmp2, 0, strpos($tmp2, "</title>") - 9);

    echo htmlspecialchars_decode($tmp);
}
相关问题