Twitter $ получить помощь - PullRequest
       6

Twitter $ получить помощь

0 голосов
/ 27 августа 2010

Просто интересно, может ли кто-нибудь помочь мне со следующей проблемой.Я наткнулся на следующий код, который извлекает последние сообщения Twitter и отображает их на сайте:

//Handle the scrolling of the tweets in the footer
$(function () {
    var tweetVP = $("#footerTweetsViewport");
    arrTweetNav = ECC.tweetArray();

    thisTweetID = arrTweetNav[0];

    $("ul#tweetControls > li").bind("click", function(e) {
        e.preventDefault();

        var thisPos = $.inArray(thisTweetID, arrTweetNav);

        if ($(this).hasClass("tweetPrev")) {
            nextPos = thisPos - 1;              
        } else {
            nextPos = thisPos + 1;
        }
        nextID = arrTweetNav[nextPos];

        //If that tweet exists in the DOM...
        if ($("#listOfTweets > #" + nextID).length) {
            //Reset the inactive buttons
            $("ul#tweetControls > li").removeClass("inactive");
            //Scroll to the destination
            tweetVP.scrollTo("#" + nextID, 200);
            //Set the thisID to the value of the nextID
            thisTweetID = nextID;
        }

        //Disable the controls if we're on the first or last tweet
        if (nextPos == arrTweetNav.length-1) {
            $("ul#tweetControls > li.tweetNext").addClass("inactive");
        } else if (nextPos == 0) {
            $("ul#tweetControls > li.tweetPrev").addClass("inactive");
        }
    }).bind("mousedown", function() {
        $(this).closest("li").addClass("click");
    }).bind("mouseup", function() {
        $(this).closest("li").removeClass("click")
    });

});

//Search the dom for twitter containers that need tweets loaded for
$(function() {
    $(".globalTweetWrapper").each(function() {
        var thisUsername = $(this).attr("class").replace("globalTweetWrapper ", "");
        var tweetContainer = $(this);
        var loadTweets = tweetContainer.find(".loadTweets");
        //Detect if we're going to flush the tweets
        var flushTweets = $.getUrlVar("flushTweets");
        if (flushTweets != 1) {
            flushTweets = 0;
        }

        $.getJSON("get-tweets.cfm?username=" + thisUsername + "&flushTweets=" + flushTweets, function(data) {
            if (data.length && loadTweets.length) {
                loadTweets.remove();

                $.each(data, function(i,item) {
                    if (tweetContainer.attr("id") == "listOfTweets") {
                        tweetContainer.append("<li class='tweetContainer' id='" + item.ID + "'>" + item.TWEET + "<small class='darkGray'>" + item.DATE + "</small></li>");
                    } else {
                        tweetContainer.append("<p class='tweetContainer'>" + item.TWEET + "</p><small class='darkGray'>" + item.DATE + "</small>");
                        if (i == 1) return false;
                    }
                });

                //Rebuild the tweet array
                arrTweetNav = ECC.tweetArray();
                thisTweetID = arrTweetNav[0];
            }
        });
    });
});

Это HTML-контейнер для твитов на сайте:

<div class="footerItem posRelative">
<h3><a href="twitter url goes here/mytwitterid" rel="external" title="Follow us on    Twitter">Follow us</a> on Twitter</h3>
<ul id="tweetControls">
<li class="tweetPrev inactive">Previous Tweet</li>
<li class="tweetNext">Next Tweet</li>
</ul>

<div id="footerTweetsViewport">
<ul id="listOfTweets" class="globalTweetWrapper">
</ul>

Мой сайт не является Coldfusion;поэтому я просто хочу изменить get-tweets.cfm и хотел бы получить некоторую помощь, пожалуйста.Я сталкивался со следующим:

//initialize a new curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'twitter url goes here/statuses/user_timeline/twitterusername.json?count=10');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);

if($content === FALSE) {
//Content couldn't be retrieved... Do something
} else {
//Content was retrieved do something with it.
}

Так что я действительно хотел бы пересобрать get-tweets.cfm в PHP-скрипт get-tweets.php;тем не менее, я не уверен, что именно мне нужно сделать, чтобы заставить это работать согласно сценарию coldfusion, поскольку все остальное в порядке?

Большое спасибо

Ответы [ 2 ]

0 голосов
/ 27 августа 2010

Новый скрипт get_tweets для получения твитов, фильтрации по нужным столбцам, кэширования (в случае сбоя в Twitter) и результатов эха.

<?php

$username = "danielgwood";
$num = 5;

$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&rpp=" . $num;

$cachefile = dirname(__FILE__)."/twitter.json";

// Get new contents
$newTweets = @file_get_contents($feed);

// Filter columns
$tweets = array();
if($newTweets !== null) {
    $newTweetsObj = json_decode($newTweets);

    foreach($newTweetsObj->results as $tweet) {
        $tweets[]['ID'] = $tweet->id;
        $tweets[]['TWEET'] = $tweet->text;
        $tweets[]['DATE'] = $tweet->created_at;
    }

    $newTweets = json_encode($tweets);
}

// Cache result
if($newTweets !== null) {
    @file_put_contents($cachefile, $newTweets);
}

$tweets = @file_get_contents($cachefile);

echo $tweets;

?>
0 голосов
/ 27 августа 2010

Twitter предоставляет твиты в формате JSON через API.Вам нужно извлечь их, кэшировать на сервере (записать в файл за пределами веб-дерева) на случай, если Twitter отключится, как это обычно происходит, а затем вызвать JSON для Javascript.* Я не проверял это, но это определенно правильно.См. bavotasan.com

$username = "your-user-name";
$num = 5;

$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&amp;rpp=" . $num;

$newfile = dirname(__FILE__)."/twitternew.json";
$file = dirname(__FILE__)."/twitter.json";

copy($feed, $newfile);

$oldcontent = @file_get_contents($file);
$newcontent = @file_get_contents($newfile);

if($oldcontent != $newcontent) {
    copy($newfile, $file);
}
$tweets = @file_get_contents($file);

echo $tweets;

. Следует отметить, что приведенное выше решение предназначено для полной замены сценария Coldfusion.Чтобы использовать отрывок PHP, который у вас уже есть, просто добавьте кеширование в файл и эхо-части.Это даст вам больше всего, если не весь путь туда.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...