使用google api在PHP中使用411内容长度错误

时间:2013-10-24 21:48:41

标签: php google-api

我正在尝试向api发送简单的帖子请求以下载报告。

收到411错误消息,其中显示“POST请求需要内容长度标题。这就是我们所知道的。”

我在这里使用这个例子。 https://code.google.com/p/google-api-adwords-php/wiki/NoClientLibrary

还尝试了新的api url https://adwords.google.com/api/adwords/cm/v201309

有没有人遇到过这个? 有什么想法吗?

谢谢!

<?php
// Provide header information.
$authToken = 'INSERT_AUTH_TOKEN_HERE';
$clientCustomerId = 'INSERT_CLIENT_CUSTOMER_ID_HERE';
$developerToken = 'INSERT_DEVELOPER_TOKEN_HERE';

// Create report definition XML.
$reportDefinition = <<<EOT
<reportDefinition xmlns="https://adwords.google.com/api/adwords/cm/v201109">
  <selector>
    <fields>CampaignId</fields>
    <fields>Id</fields>
    <fields>Impressions</fields>
    <fields>Clicks</fields>
    <fields>Cost</fields>
    <predicates>
      <field>Status</field>
      <operator>IN</operator>
      <values>ENABLED</values>
      <values>PAUSED</values>
    </predicates>
  </selector>
  <reportName>Custom Adgroup Performance Report</reportName>
  <reportType>ADGROUP_PERFORMANCE_REPORT</reportType>
  <dateRangeType>LAST_7_DAYS</dateRangeType>
  <downloadFormat>CSV</downloadFormat>
</reportDefinition>
EOT;

// Create parameters.
$params = array('__rdxml' => $reportDefinition);

// Create headers.
$headers = array();
$headers[]= 'Authorization: GoogleLogin auth=' . $authToken;
$headers[]= 'clientCustomerId: ' . $clientCustomerId;
$headers[]= 'developerToken: ' . $developerToken;
$headers[]= 'content-length: ' . trim(strlen(print_r($params, true)));
$headers[]= 'Content-Type: application/x-www-form-urlencoded';

$downloadPath = 'report.csv';
$url = 'https://adwords.google.com/api/adwords/reportdownload/v201109';

$file = fopen($downloadPath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($file);

if ($code == 200) {
  printf("Report downloaded to: %s\n", $downloadPath);
} else {
  $file = fopen($downloadPath, 'r');
  $error = fread($file, 1024);
  fclose($file);
  printf("Error: %s\n", $error);
}

0 个答案:

没有答案