1

我正在使用以下代码来解析来自 twitter 帐户的最新推文:

    $host = "http://search.twitter.com";
    $filename = "/search.json";

    $opts = array('http' => array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n"
    ));
    $context = stream_context_create($opts);

    $search = "mashable";
    $search = str_replace(" ", "%20", $search);
    $count = "10";

    $a = "$host$filename?q=$search&rpp=$count&include_entities=true";
    echo "$a\n";
    $json = file_get_contents($a, false, $context);

    $obj = json_decode($json, true);
    $id = $obj['results'][0]['id'];
    $tweet = $obj['results'][0]['text'];
    $user = $obj['results'][0]['from_user'];
    $to_user = $obj['results'][0]['to_user'];
    $media_url = $obj['results'][0]['media_url'];

    #echo $json;
    echo "<br /><br />";
    echo "searching for $search\n tweet count: $count\n";
    echo "<br /><br /><b>tweets</b><br />";
    echo "tweet_id: $id <br />";
    echo "user: $user <br />";
    echo "Tweet: $tweet<br />";
    echo "to_user: $to_user <br />";
    echo "media: $media_url";
    echo ""

?>

我想提取以下值: - 用户名(发件人) - 推文(文本) - 给用户(如果是回复) - 媒体附件(图片)

该代码正在运行,但由于某种原因,我只收到最新的推文而不是数字 ($count) 值。我也无法收到推文的 media_url 值。我的问题是:如何?

4

2 回答 2

1

您必须遍历结果才能获得所有结果而不是其中之一,例如:

$host = "http://search.twitter.com";
$filename = "/search.json";

$opts = array('http' => array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n"
));
$context = stream_context_create($opts);

$search = "mashable";
$search = str_replace(" ", "%20", $search);
$count = "10";

$a = "$host$filename?q=$search&rpp=$count&include_entities=true";
echo "$a\n";
$json = file_get_contents($a, false, $context);

$obj = json_decode($json, true);

foreach ($obj['results'] as $index => $result) {
    $id = $result['id'];
    $tweet = $result['text'];
    $user = $result['from_user'];
    $to_user = $result['to_user'];
    $media_url = $result['media_url'];

    #echo $json;
    echo "<br /><br />";
    echo "searching for $search\n tweet count: $count\n";
    echo "<br /><br /><b>tweets</b><br />";
    echo "tweet_id: $id <br />";
    echo "user: $user <br />";
    echo "Tweet: $tweet<br />";
    echo "to_user: $to_user <br />";
    echo "media: $media_url";
    echo "";
}

另外,当我做 a 时,print_r($obj);我看不到任何media_url价值 - 看起来 Twitter 没有返回它,这就是你无法访问它的原因。

于 2013-01-22T10:36:42.337 回答
0

我找到了接收每条推文的 media_url 参数的解决方案:

$media_url = $result['entities']['media'][0]['media_url']
于 2013-01-22T12:19:30.293 回答