2013-02-07 39 views
1

我只想顯示某些東西從這樣的頁面:http://sc2ranks.com/api/psearch/am/MxGPezz/1t/division/Felanis%20Sierra?appKey=sentinelgaming.net。到目前爲止,我能夠顯示一些東西,但它甚至不是正確的數字,使用下面的php。有人能告訴我如何從這個XML網頁顯示這個播放器的「成就點」嗎?XML-JSON內容協商

$url = 'http://sc2ranks.com/api/psearch/am/MxGPezz/1t/division/Felanis%20Sierra?appKey=sentinelgaming.net'; 
$xml = file_get_contents($url); 

echo $xml->achievement-points; 

由於

+0

'$ XML = [{ 「achievement_points」:580, 「character_code」:0, 「團隊」:{ 「點」:1308 「贏」:127,「損失」:104,「division_id」:351726,「division_name」:「Division Felanis Sierra」,「id」:12366704},「region」:「我們」,「bnet_id」:2868603,名稱「:」MxGPezz「,」id「:3416151}]'(length = 233)'奇怪! – SparKot

+0

並不奇怪 - 服務器正在使用內容協商。 –

回答

1

的內容類型此文件的視Accept頭或format查詢參數而變化。看來你可以至少檢索XML或JSON。

file_get_contents()得到的將是JSON,因爲它不包括Accept請求頭默認,但是從瀏覽器默認將XML因爲瀏覽器通常包括在他們的Accept申請頭的XML mime類型。

要獲得JSON:

$url = 'http://sc2ranks.com/api/psearch/am/MxGPezz/1t/division/Felanis%20Sierra?appKey=sentinelgaming.net'; 

// &format=json is not strictly necessary, 
// but it will give you fewer surprises 
$json = file_get_contents($url.'&format=json'); 
$records = json_decode($json); 
echo $records[0]->achievement_points, "\n"; 

要獲取XML:

$sxe = simplexml_load_file($url.'&format=xml'); 
echo (string) $sxe->record->{'achievement-points'}, "\n"; 

要使用$sxe對象看this SimpleXML cheat sheet

而不是使用format參數,您可以設置Accept標題。您還可以添加一些抽象來獲取url,以便您可以檢索內容類型和編碼。看下面的例子。

function get_url($url, $context=null) { 
    $response = file_get_contents($url, false, $context); 
    $ctypeheaders = preg_grep('/^Content-Type:\s/i', $http_response_header); 
    $ctype = NULL; 
    if ($ctypeheaders) { 
     $ctype = end($ctypeheaders); 
     $ctype = end(explode(':', $ctype, 2)); 
     $ctype = explode(';', $ctype, 2); 
     $charset = isset($ctype[1]) ? $ctype[1] : ''; 
     if ($charset && preg_match('/charset\s*=\s*([^\s]+)/i', $charset, $matches)) { 
      $charset = $matches[1]; 
     } 
     $ctype[1] = $charset; 
     $ctype = array_map('trim', $ctype); 
    } 
    return array($response, $ctype); 
} 

然後可以使用get_url()像這樣:

// With no accept header, just see what we get: 
list($content, $contenttype) = get_url($url); 
list($type, $encoding) = $contenttype; 
// $type will be 'application/xml' or 'application/json' 
// $encoding is very handy to know too 

// Or we can specify an accept header: 
$opt_accept_xml = stream_context_create(array(
    'http' => array(
     'header' => "Accept: application/xml\r\n" 
    ) 
)); 

list($content, $contenttype) = get_url($url, $opt_accept_xml); 
+0

我無法獲得任何展示,因爲我認爲這是朝正確方向邁出的一步。無論我用這種方法使用什麼樣的變化都會變成空白。 –

+0

'file_get_contents()'是一個字符串 - 你必須解析它。另外,這個url將json返回給PHP,而不是XML。查看更新的答案。 –

+0

哦,我的天啊,非常感謝弗朗西斯,我真的很感激!我第一次看到它多次發佈這個問題的工作。只有回答是有道理的! –

0

也許:

echo $xml->record[0]->achievement-points; 
+0

由於某些原因,即使「0」不是該用戶的成績點的正確數量,也會出現「0」。 –