Google自定义搜索API通过cURL通过php以编程方式添加注释

Google自定义搜索API通过cURL通过php以编程方式添加注释,php,xml,curl,google-custom-search,Php,Xml,Curl,Google Custom Search,我试图通过使用php和cURL发布xml,以编程方式将注释站点添加到我的google自定义搜索引擎中进行搜索。根据他们的开发人员文档,我需要做的就是: POST http://www.google.com/cse/api/default/annotations/ Content-Type: text/xml Authorization: GoogleLogin auth="IM6F7Cx2fo0TAiwlhNVdSE8Ov8hw6aHV" <Batch> <Add> &

我试图通过使用php和cURL发布xml,以编程方式将注释站点添加到我的google自定义搜索引擎中进行搜索。根据他们的开发人员文档,我需要做的就是:

POST http://www.google.com/cse/api/default/annotations/
Content-Type: text/xml
Authorization: GoogleLogin auth="IM6F7Cx2fo0TAiwlhNVdSE8Ov8hw6aHV"

<Batch>
<Add>
<Annotations>
  <Annotation about="http://www.solarenergy.org/*">
    <Label name="_cse_solar_example"/>
  </Annotation>
  <Annotation about="http://www.solarfacts.net/*">
    <Label name="_cse_solar_example"/>
  </Annotation>
  <Annotation about="http://en.wikipedia.org/wiki/*">
    <Label name="_cse_exclude_solar_example"/>
  </Annotation>

  </Annotations>
  </Add>
  </Batch>
然而,当我使用下面的代码时,我得到一个错误411,POST请求需要一个内容长度头

function getAuthorizationToken(){
$ch = curl_init();
$url = 'https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email=***&Passwd=***&service=cprose&source=***';
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$authTokenData = curl_exec($ch);
$authTokenArray = explode('Auth=', $authTokenData);
$authToken = $authTokenArray[1];
curl_close($ch);
return $authToken;
}

$authToken = getAuthorizationToken();

$url = 'http://www.google.com/cse/api/default/annotations/';
$xml_data = '<?XML version="1.0"?>
<Batch>
  <Add>
    <Annotations>
      <Annotation about="http://www.solarenergy.org/*">
        <Label name="_cse_solar_example"/>
      </Annotation>
      <Annotation about="http://www.solarfacts.net/*">
        <Label name="_cse_solar_example"/>
      </Annotation>
      <Annotation about="http://en.wikipedia.org/wiki/*">
        <Label name="_cse_exclude_solar_example"/>
      </Annotation>
     </Annotations>
  </Add>
</Batch>';
$length = strlen($xml_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Authorization: GoogleLogin auth=".        $authToken, "Content-Type: text/xml", "Content-Length: " . $length));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
$result = curl_exec($ch);
curl_close($ch);

echo $result;
我已经为这个问题挣扎了很长一段时间,我非常感谢任何帮助


谢谢

尝试将注释发送到http://www.google.com/cse/api/default/annotations/solar_example 并从curl选项中删除内容长度标题。应该是这样的:

curl_setopt ($ch, CURLOPT_HTTPHEADER, Array(
    "Authorization: GoogleLogin auth=". $authToken, 
    "Content-Type: text/xml"
));

这对我很管用。

你可能还改变了什么吗?不幸的是,在你的建议下更改了我的代码之后,它对我仍然不起作用。不,我没有。其他一切似乎都一样。