【问题标题】:Using PHP and the new Twitter API使用 PHP 和新的 Twitter API
【发布时间】:2013-03-01 11:55:29
【问题描述】:

由于新的 Twitter API,我正在使用 PHP 在我的网页上使用 PHP 显示 1 条最新推文。

目前我已经让它工作了,所以推文只是作为一个简单的文本字符串输出。我的问题是如何控制输出的 HTML?如果推文中说明了主题标签或网址,我希望能够将链接显示为链接。我该怎么做?

到目前为止,这是我的代码,它将字符串作为推文输出到我的页面中:

function get_tweet() {

require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'secret',
'consumer_secret' => 'secret',
'user_token' => 'secret',
'user_secret' => 'secret',
'curl_ssl_verifypeer' => false
));

$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'evanrichards',
'count' => '1'));

$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
echo($tweets[0]['text']);

}

【问题讨论】:

  • 最好的办法是使用正则表达式。我用于我的网站的正则表达式是/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i,它被替换为<a target=\"_blank\" href=\"$1\">$1</A>。您可以为此使用 php preg_replace() 函数。但我的正则表达式只将 url 转换为链接。您可能需要另一个用于哈希标签。我会调查,因为我有兴趣自己添加它们。也许可以为@names 添加第三个链接到个人资料。

标签: php html twitter


【解决方案1】:

这里是一些示例代码,用于用 php 中的链接替换链接、主题标签和 attags

$tweet = "@george check out http://www.google.co.uk #google";

//Convert urls to <a> links
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);

//Convert hashtags to twitter searches in <a> links
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);

//Convert attags to twitter profiles in <a> links
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);

echo $tweet;

这给出了输出

<a href="http://www.twitter.com/george">@george</a> check out <a target="_blank" href="http://www.google.co.uk">http://www.google.co.uk</a> <a target="_new" href="http://twitter.com/search?q=google">#google</a>

因此您可以将代码更改为

function get_tweet() {

  require 'tmhOAuth.php';
  require 'tmhUtilities.php';

  $tmhOAuth = new tmhOAuth(array(
  'consumer_key' => 'secret',
  'consumer_secret' => 'secret',
  'user_token' => 'secret',
  'user_secret' => 'secret',
  'curl_ssl_verifypeer' => false
  ));

  $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
  'screen_name' => 'evanrichards',
  'count' => '1'));

  $response = $tmhOAuth->response['response'];
  $tweets = json_decode($response, true);

  $tweet = $tweets[0]['text'];
  $tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
  $tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
  $tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
  echo($tweet);

}

我确信正则表达式可以改进。

或者更好的是,您可以将其拆分为自己的功能。

function linkify_tweet($tweet) {

  $tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
  $tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
  $tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);

  return $tweet;

}

function get_tweet() {

  require 'tmhOAuth.php';
  require 'tmhUtilities.php';

  $tmhOAuth = new tmhOAuth(array(
  'consumer_key' => 'secret',
  'consumer_secret' => 'secret',
  'user_token' => 'secret',
  'user_secret' => 'secret',
  'curl_ssl_verifypeer' => false
  ));

  $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
  'screen_name' => 'evanrichards',
  'count' => '1'));

  $response = $tmhOAuth->response['response'];
  $tweets = json_decode($response, true);

  echo(linkify_tweet($tweets[0]['text']));

}

【讨论】:

  • 太棒了!工作一种享受!我确实评论它没有用,但这是我的错误。非常感谢!
  • 没问题很高兴我能帮上忙。
【解决方案2】:

一个简单的正则表达式可以在大多数情况下工作。但 Twitter 实体会为您解决解析问题,并为您提供有关链接、用户名等的更多信息。

在此处查看完整文档:https://dev.twitter.com/overview/api/entities-in-twitter-objects

要格式化文本,请获取您需要进行的所有替换的列表,然后以相反的顺序进行替换(因此在文本展开后偏移保持正确)。

<?php
function twitter_format($tweet) {
    $text = $tweet['text'];
    $entities = isset($tweet['entities']) ? $tweet['entities'] : array();

    $replacements = array();
    if (isset($entities['hashtags'])) {
        foreach ($entities['hashtags'] as $hashtag) {
            list ($start, $end) = $hashtag['indices'];
            $replacements[$start] = array($start, $end,
                "<a href=\"https://twitter.com/search?q={$hashtag['text']}\">#{$hashtag['text']}</a>");
        }
    }
    if (isset($entities['urls'])) {
        foreach ($entities['urls'] as $url) {
            list ($start, $end) = $url['indices'];
            // you can also use $url['expanded_url'] in place of $url['url']
            $replacements[$start] = array($start, $end,
                "<a href=\"{$url['url']}\">{$url['display_url']}</a>");
        }
    }
    if (isset($entities['user_mentions'])) {
        foreach ($entities['user_mentions'] as $mention) {
            list ($start, $end) = $mention['indices'];
            $replacements[$start] = array($start, $end,
                "<a href=\"https://twitter.com/{$mention['screen_name']}\">@{$mention['screen_name']}</a>");
        }
    }
    if (isset($entities['media'])) {
        foreach ($entities['media'] as $media) {
            list ($start, $end) = $media['indices'];
            $replacements[$start] = array($start, $end,
                "<a href=\"{$media['url']}\">{$media['display_url']}</a>");
        }
    }

    // sort in reverse order by start location
    krsort($replacements);

    foreach ($replacements as $replace_data) {
        list ($start, $end, $replace_text) = $replace_data;
        $text = mb_substr($text, 0, $start, 'UTF-8').$replace_text.mb_substr($text, $end, NULL, 'UTF-8');
    }
    return "<p>$text</p>";
}

echo twitter_format($tweets[0]);

【讨论】:

  • +1 谢谢你,您可能只想在 foreach 循环之前使用if(isset($entities['hashtags'])... 来检查是否存在主题标签等
  • 我在使用 substr_replace 时也遇到了问题,因为传入的字符串似乎是 UTF-8。通过在运行 substr_replace 之前转换为 iso-8859-1 然后返回到 UTF-8 来解决,但猜想这并不花哨;)
  • 显然偏移量是字符,而不是字节。您是否尝试使用 mb_* 函数,而不是转换为 iso-8859-1?类似$text = mb_substr($text, 0, $start).$replace_text.mb_substr($text, $start+$length);
猜你喜欢
  • 2015-08-15
  • 2011-09-20
  • 2012-12-01
  • 2011-04-14
  • 2017-12-07
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
相关资源
最近更新 更多