2009-10-15 45 views
0

當我的更新字符串中有一個&時,我對Twitter API的自動調用會導致問題。正確地結束編碼&for twitter post

在我使用CURL調用Twitter API之前,如何正確編碼包含&的更新字符串$update

// Set username and password for twitter API 
     $username = '***'; 
     $password = '***'; 

     // The twitter API address 
     $url = 'http://twitter.com/statuses/update.xml'; 

     // Alternative JSON version 
     // $url = 'http://twitter.com/statuses/update.json'; 

     // Set up and execute the curl process 
     $curl_handle = curl_init(); 

     curl_setopt($curl_handle, CURLOPT_URL, "$url"); 
     curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10); 
     curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($curl_handle, CURLOPT_POST, 1); 
     curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$update"); 
     curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password"); 

     $buffer = curl_exec($curl_handle); 

     curl_close($curl_handle); 

     // check for success or failure 

     if (empty($buffer)) 
     { 
      echo 'error?!'; 
     } 
+5

通過不安全的HTTP電線經過您的用戶名和密碼Twitter是一個真是糟糕的主意。 – 2009-10-15 14:52:37

+0

請給我一個安全的方法,我會用它。 :) – ian 2009-10-15 14:53:57

+0

將「http」更改爲「https」 – Greg 2009-10-15 14:58:43

回答

1

你有兩個選擇,urlencode()http_build_query()

// Using urlencode() 
$update = 'this & that'; 
echo "status=" . urlencode($update); 

// Using http_build_query() 
$postFields = array(
    'status' => $update 
); 
echo http_build_query($postFields); 
1

運行它通過urlencode()或使用http_build_query()

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=" . urlencode($update)); 

// or 

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query(array("status" => $update));