2011-07-15 48 views
1

添加註釋通過編程的PHP我想通過編程使用PHP和捲曲POST操作XML來註解(網站進行查詢)添加到我的谷歌自定義搜索引擎。根據他們的開發者文檔,所有我需要做的是:谷歌自定義搜索API通過捲曲

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請求需要一個Content-Length頭」

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; 

我一直在努力與這個問題了很長一段時間,我將不勝感激任何幫助。

謝謝

回答

0

嘗試發送註釋http://www.google.com/cse/api/default/annotations/solar_example和捲曲選項中刪除Content-Length頭。它應該看起來像這樣:

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

它適用於我。

+0

你可能改變什麼嗎?它仍然沒有工作,我通過你的建議改變我的代碼後,遺憾的是沒有 – Lee

+0

,我沒有。其他一切似乎都是一樣的。 –