的內容類型此文件的視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);
'$ 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
並不奇怪 - 服務器正在使用內容協商。 –