PHP JSON Twitter Feed Improvement

2019-06-14 06:48发布

I am working on a PHP twitter feed for my web-site. So far I have figured out how to output date, but what I'm looking to do is pick out the urls and hyperlink them. I also would like to pick out the #hashtags, hyperlink them to search twitter. I'm just starting to learn PHP, so any help would be appreciated.

<?php
    $count = 5;
    $tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/atrueresistance.json?count=".$count."" ));
    for ($i=1; $i <= $count; $i++){   
        echo "<div class='tweet'>".$tweet[($i-1)]->text."                
            <div class='tweet_date'>". date("M \- j",strtotime($tweet[($i-1)]->created_at))."
            </div>
        </div>";   
     }    
?>

1条回答
女痞
2楼-- · 2019-06-14 07:49

Since no one is responding to this, I figured it is about time I put what code I came up with.

Enjoy!

<?php

$count = 5;
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/atrueresistance.json?count=".$count."" ));
for ($i=1; $i <= $count; $i++){
    //Assign feed to $feed
    $feed = $tweet[($i-1)]->text;
    //Find location of @ in feed
    $feed = str_pad($feed, 3, ' ', STR_PAD_LEFT);   //pad feed     
    $startat = stripos($feed, '@'); 
    $numat = substr_count($feed, '@');
    $numhash = substr_count($feed, '#'); 
    $numhttp = substr_count($feed, 'http'); 
    $feed = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "<a href=\"\\0\">\\0</a>", $feed);
    $feed = preg_replace("(@([a-zA-Z0-9\_]+))", "<a href=\"http://www.twitter.com/\\1\">\\0</a>", $feed);
    $feed = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', $feed);
    echo "<div class='tweet'>".$feed.  "<div class='tweet_date'>". date("M \- j",strtotime($tweet[($i-1)]->created_at))."
            </div></div>";      
    }?>
查看更多
登录 后发表回答