1

我希望只显示以下页面中的某些内容:http ://sc2ranks.com/api/psearch/am/MxGPezz/1t/division/Felanis%20Sierra?appKey=sentinelgaming.net 。到目前为止,我可以使用下面的 php 显示一些东西,但它甚至不是正确的数字。有人能告诉我如何从这个 XML 网页显示这个播放器的“成就点”吗?

$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,因为它不包含请求标头,但来自浏览器的默认值将是 XML,因为浏览器通常在其请求标头Accept中包含 XML mime 类型。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 回答
0

也许:

    echo $xml->record[0]->achievement-points;
于 2013-02-07T20:24:53.170 回答