PHP:获取网站的特定内容

时间:2014-06-12 12:24:05

标签: php file web

我希望将网站的特定内容转换为数组。

我有大约20个网站以我喜欢的其他方式获取内容和输出。
只有端口总是在变化(不是27015,而不是27016左右......)

This is just one: SOURCE-URL of Content

现在,我在PHP中使用此代码来获取Gameicon" cs.png",但图标长度不同 - 所以它不是最佳方式,或者? : - /

$srvip = '148.251.78.214';
$srvlist = array('27015');
foreach ($srvlist as $srvport) {
    $source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');  
    $content = array(
                   "icon" => substr($source, strpos($source, 'game_icons64')+13, 6),
               );
    echo $content[icon];
}

感谢您的帮助,我上一次PHP工作有些日子过去了:P

1 个答案:

答案 0 :(得分:1)

您只需要查找"之后的第一个game_icons64,并在那里阅读。

$srvip = '148.251.78.214';
$srvlist = array('27015');
foreach ($srvlist as $srvport) {
    $source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');  

    // find the position right after game_icons64/
    $first_occurance = strpos($source, 'game_icons64')+13;

    // find the first occurance of " after game_icons64, where the src ends for the img
    $second_occurance = strpos($source, '"', $first_occurance);

    $content = array(
                  // take a substring starting at the end of game_icons64/ and ending just before the src attribute ends
                   "icon" => substr($source, $first_occurance, $second_occurance-$first_occurance),
               );
    echo $content['icon'];
} 

此外,由于您使用了[icon]而非['icon']

,因此出现了错误

编辑以匹配涉及多个字符串的第二个请求

$srvip = '148.251.78.214';
$srvlist = array('27015');

$content_strings = array( );

// the first 2 items are the string you are looking for in your first occurrence and how many chars to skip from that position
// the third is what should be the first char after the string you are looking for, so the first char that will not be copied
// the last item is how you want your array / program to register the string you are reading
$content_strings[] = array('game_icons64', 13, '"', 'icon');
// to add more items to your search, just copy paste the line above and change whatever you need from it

foreach ($srvlist as $srvport) {
    $source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');  

    $content = array();

    foreach($content_strings as $k=>$v)
    {
        $first_occurance = strpos($source, $v[0])+$v[1];

        $second_occurance = strpos($source, $v[2], $first_occurance);

        $content[$v[3]] = substr($source, $first_occurance, $second_occurance-$first_occurance);
    }

    print_r($content);
}