1

http://sc2ranks.com/api/psearch/am/MxGPezz/1t/division/Felanis%20Sierra?appKey=sentinelgaming.netのようなページから特定のもののみを表示しようとしています。これまでのところ、以下のphpを使用して、何かを表示することはできますが、正しい番号でさえありません。この XML Web ページからこのプレーヤーの「達成ポイント」を表示する方法を教えてもらえますか?

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

echo $xml->achievement-points;

ありがとう

4

2 に答える 2

1

このファイルのコンテンツタイプは、Acceptヘッダーまたはformatクエリパラメータによって異なります。少なくともXMLまたはJSONを取得できるようです。

file_get_contents()リクエストヘッダーが含まれていないため、デフォルトはJSONになりますがAccept、ブラウザは通常、リクエストヘッダーにXML mimeタイプが含まれているため、ブラウザからのデフォルトはXMLになりますAccept

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オブジェクトを使用するには、このSimpleXMLチートシートを参照してください。

パラメータを使用する代わりに、ヘッダー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);
于 2013-02-07T20:33:50.763 に答える