views:

74

answers:

2

My automated call to the Twitter API causes problems when my update string has a & in it.

How do I properly encode my update string $update that contains a & before I use CURL to call the Twitter API?

// 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?!';
     }
+1  A: 

Run it through urlencode() or use 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));
Greg
+1  A: 

You have two choices, urlencode() or 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 );
Peter Bailey