2013-05-10 161 views
-1

我在這裏很難從API獲取一些json數據。基本上我想獲取文件內容,然後將「meta_game」分配給一個變量,我也希望將「channel_count」分配給一個變量。正如你在這裏看到的,我爲兩個實例嘗試了兩種不同的方法,目前都不工作。從外部URL檢索Json數據

$json = file_get_contents($chan); 
$json_data = unserialize($json); 
$gameName = json_decode($json)->meta_game; 
$viewerCount = $json_data['channel_count']; 

下面是一個URL的例子:http://api.justin.tv/api/stream/list.json?channel= +頻道名稱。

+0

您是否嘗試運行幹測試以查看您獲得的json_data變量的回報? – 2013-05-10 08:45:49

+0

我不明白你怎麼可能甚至說出你剛纔所說的話。如何在本網站上提出一個問題被引用爲懶惰?顯然,我無法重現我所尋找的東西,這就是我來到這裏的原因。 – 2013-05-10 08:54:04

+0

「這裏是我的代碼,我不會在意它如何不能滿足我的需求,猜猜是什麼錯誤並修復它。」 – 2013-05-10 08:55:09

回答

3

爲什麼要反序列化數據?它不需要

$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel=' . $channelName); 
$jsonData = json_decode($json); 

$gameName = $jsonData->meta_game; 

$viewerCount = $jsonData->channel_count; 

當然,你可能需要通過$jsonData對象,檢查路徑找到你的最終值,因爲我沒有分析它並不能保證他們在第一個節點。

更新:因爲我不會放過任何東西,我檢查這個,看看來自API的響應是

由於它首先返回一個數組,你的路會

$jsonData[0]->channel->meta_game; 

$jsonData[0]->channel_count; 

假設你只有在響應1路

+0

謝謝,我真的很感謝幫助。 – 2013-05-10 08:57:34

0
(function($){ 
    $.fn.fetch = function() { 
     $.ajaxSetup({ cache: true }); 
     //var optionsWithDefaults = $.extend(defaults, options); 
     return this.each(function() { 
      var obj = []; 
      $.getJSON(' http://api.justin.tv/api/stream/list.json?channel=xxx', 
       function(data) { 
        $.each(data, function(i, feed) { 
         if(feed.channel_count !== undefined) { 
          obj.push(feed.channel_count); 
         } 
        }); 
       } 
      ); 
     }); 
    }; 
})(jQuery); 
1

你可以試試下面的代碼

<?php 
$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel='); 
$gameName = json_decode($json,true); 
$new_arr = array(); 
foreach($gameName as $g){ 
print_r($g['channel']['meta_game']); 
array_push($new_arr,$g['channel']['meta_game']); 
}  
?>