2013-01-22 54 views
1

我用下面的代碼來解析從Twitter帳戶的最新的鳴叫:PHP獲取最新的鳴叫JSON格式

$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 "" 

?> 

我想提取以下值: - 用戶名(發件人) - 鳴叫(文本) - 用戶(如果是回覆) - 媒體附件(圖片)

的代碼工作,但由於某種原因,我只收到了最新的tweet,而不是數($計數)值。我也無法收到推文的media_url值。我的問題是:如何?

回答

0

我找到了解決接收各鳴叫MEDIA_URL參數:

$media_url = $result['entities']['media'][0]['media_url'] 
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正在返回,這就是爲什麼你無法訪問它。

+0

謝謝您的回答!如果您使用'GettyImages'代碼,您會在第二條推文中看到參數media_url。 –