I want to subscribe a YouTube Channel through the GData API via PHP.

Documentation

How can i do this post in PHP?

I tried it like this but the page keeps loading forever:

<?php

session_start();

include 'gdata.php' // For $DEVKEY

function post_xml($url, $xml) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, Array(
  "Content-Type: application/atom+xml",
  "Content-Length: 1024",
  "Authorization: Bearer $token",
  "GData-Version: 2",
  "X-GData-Key: key=$DEVKEY"));
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $xml );
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  $result = curl_exec($ch);
  $info = curl_getinfo($ch);
  curl_close($ch);
  return $result;
}    

$token = $_SESSION['token'];

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
  xmlns:yt="http://gdata.youtube.com/schemas/2007">
    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat"
      term="channel"/>
    <yt:username>GoogleDevelopers</yt:username>
</entry>';

$url = 'https://gdata.youtube.com/feeds/api/users/default/subscriptions';

echo post_xml($url, $xml);

?>

In HttpRequester i already managed it to do a HTTP Post Request and it worked. I think the problem is the content of the Request. How do i properly give the text which is in "Content" (look at the screenshot) via PHP (cURL)?

HttpRequester

Thanks :)

有帮助吗?

解决方案

Just put the $xml as POSTFIELDS and it should work:

curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

And add the correct content-length:

"Content-Length: ".strlen($xml),

When you're planning to do more, like PUT-requests with data and just lots of REST-requests, I would suggest to use some kind of package like Httpful. Curl has it's pitfalls...

其他提示

You can look at the code below, hope it will help

 $headers = array(
        "Content-type: text/xml",
        "Content-length: " . strlen($xml),
        "Connection: close",
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $res = curl_exec($ch);
    curl_close($ch);

    return json_decode($res);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top