我正在使用以下代码来解析来自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值。我的问题是:怎么样?
答案 0 :(得分: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 "";
}
另外,当我做print_r($obj);
时,我看不到任何media_url
值 - 看起来不像Twitter那样,这就是你无法访问它的原因。< / p>
答案 1 :(得分:0)
我找到了接收每条推文的media_url参数的解决方案:
$media_url = $result['entities']['media'][0]['media_url']