Php Twitter Post Image

时间:2017-03-29 13:39:45

标签: php twitter

我尝试使用php在Twitter上发布媒体。我可以发布推文,但没有看到图像。你能帮帮我吗?

<?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();
?>

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();
    }