【问题标题】:PHP Post with Header and XML Content带有标题和 XML 内容的 PHP 发布
【发布时间】:2014-04-21 22:53:41
【问题描述】:

我想通过 PHP 的 GData API 订阅一个 YouTube 频道。

我怎样才能用 PHP 写这篇文章?

我试过这样,但页面一直在加载:

<?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);

?>

在 HttpRequester 中,我已经管理它来执行 HTTP Post 请求并且它有效。我认为问题在于请求的内容。如何通过 PHP (cURL) 正确给出“内容”中的文本(看截图)?

谢谢:)

【问题讨论】:

    标签: php post youtube header gdata


    【解决方案1】:

    只需将$xml 设置为 POSTFIELDS 就可以了:

    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    

    并添加正确的内容长度:

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

    当您打算做更多事情时,例如带有数据的 PUT 请求和大量 REST 请求,我建议使用某种包,例如 Httpful。卷曲有它的陷阱......

    【讨论】:

    • 它一直在加载:/
    • 太糟糕了,我遇到了同样的问题(虽然 API 不同,但是使用 POST 和 XML 数据),这为我解决了问题。 API 调用是否应该返回任何内容?因为您要求任何响应正文 (CURLOPT_RETURNTRANSFER ),我可以想象只有 HTTP 200 响应。
    • 哦,我认为 PHP 仍然试图做所有的帖子,因为我的整个 apache 服务器很慢。我重新启动,它现在可以工作了。谢谢:)
    【解决方案2】:

    你可以看看下面的代码,希望对你有帮助

     $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 2012-12-26
      • 2013-03-07
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多