2017-03-29 82 views
1

我嘗試使用php在Twitter上發佈媒體。我可以發佈推文,但圖片沒有看到。你可以幫幫我嗎?Php Twitter Post Image

<?php 
require_once('TwitterAPIExchange.php'); 
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/ 
$settings = array(
    'oauth_access_token' => "", 
    'oauth_access_token_secret' => "", 
    'consumer_key' => "", 
    'consumer_secret' => "" 
); 

$media_id = '847072976486858753'; 
$url = "https://api.twitter.com/1.1/statuses/update.json"; 
$twitter = new TwitterAPIExchange($settings); 
$requestMethod = 'POST'; 
$response = $twitter->setPostfields(
    array('status' => 'Test Tweet', 'media_ids' => $media_id) 
)->buildOauth($url, $requestMethod) 
    ->performRequest(); 
?> 

回答

0

您錯過了圖像處理部分。

$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json"; 
$requestMethod = "POST"; 

$tweetmsg = $_POST['post_description']; 
$twimg = $_FILES['pictureFile']['tmp_name']; 

    $postfields = array(
     'status' => $tweetmsg, 
     'media[]' => '@' . $twimg 
    ); 
    try { 
     $twitter = new TwitterAPIExchange($settings); 
     $twitter->buildOauth($url_media, $requestMethod) 
       ->setPostfields($postfields) 
       ->performRequest(); 

     echo "You just tweeted with an image"; 
    } catch (Exception $ex) { 
     echo $ex->getMessage(); 
    } 
+1

update_with_media端點已折舊。 –

1

你的代碼看起來不錯,我假設你使用的$ media_id是有效的?這裏有一些代碼可以首先處理圖片上傳,然後發佈推文。

// send image to Twitter first 
$url = 'https://upload.twitter.com/1.1/media/upload.json'; 
$requestMethod = 'POST'; 

$image = 'full/path/to/image.jpg'; 

$postfields = array(
    'media' => base64_encode(file_get_contents($image)) 
); 

$response = $twitter->buildOauth($url, $requestMethod) 
    ->setPostfields($postfields) 
    ->performRequest(); 

// get the media_id from the API return 
$media_id = json_decode($response)->media_id; 

// then send the Tweet along with the media ID 
$url = 'https://api.twitter.com/1.1/statuses/update.json'; 
$requestMethod = 'POST'; 

$postfields = array(
    'status' => 'My amazing tweet' 
    'media_ids' => $media_id, 
); 

$response = $twitter->buildOauth($url, $requestMethod) 
    ->setPostfields($postfields) 
    ->performRequest();