从网站获取随机网址

时间:2010-12-18 19:12:29

标签: php parsing

我想在http://public-domain-content.com上搜索链接数或网址数 并将它们存储在一个数组中,然后从数组中随机选择任何一个,只显示或回显

我怎么能在php

中做到这一点

1 个答案:

答案 0 :(得分:2)

如果我理解了您的要求,可以使用file_get_contents();

来实现

使用file_get_contents($url)后,它会为您提供一个字符串,您可以循环搜索空格的结果字符串,以区分单词。计算单词数,并相应地将单词存储在数组中。然后使用array_rand()

从数组中选择一个随机元素

但是,有时file_get_contents()存在安全问题。 您可以使用以下函数覆盖它:

function get_url_contents($url)
{
    $crl = curl_init();
    $timeout = 5;
    curl_setopt ($crl, CURLOPT_URL,$url);
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $ret = curl_exec($crl);
    curl_close($crl);

    return $ret;
}

http://php.net/manual/en/function.curl-setopt.php< ---关于curl的解释

示例代码:

$url = "http://www.xxxxx.xxx";     //Set the website you want to get content from
$str = file_get_contents($url);    //Get the contents of the website
$built_str = "";                   //This string will hold the valid URLs

$strarr = explode(" ", $str);      //Explode string into array(every space a new element)

for ($i = 0; $i < count($strarr); $i++)  //Start looping through the array
{
    $current = @parse_url($strarr[$i])   //Attempt to parse the current element of the array

    if ($current)                        //If parse_url() returned true(URL is valid)
    {
        $built_str .= $current . " ";    //Add the valid URL to the new string with " "
    }

    else
    {
        //URL invalid. Do something here
    }

}

$built_arr = explode(" ", $built_str)   //Same as we did with $str_arr. This is why we added a space to $built_str every time the URL was valid. So we could use it now to split the string into an array

echo $built_arr[array_rand($built_arr)]; // Display a random element from our built array

还有一个更加扩展的版本来检查网址,你可以在这里探讨:

http://forums.digitalpoint.com/showthread.php?t=326016

祝你好运。