獲取隨機地址我要搜索的鏈接或URL數量上http://public-domain-content.com 並將它們存儲在一個數組,然後就隨機選擇從陣列中的任何一個,只是顯示或回聲從網站
我如何能做到這一點的PHP的
獲取隨機地址我要搜索的鏈接或URL數量上http://public-domain-content.com 並將它們存儲在一個數組,然後就隨機選擇從陣列中的任何一個,只是顯示或回聲從網站
我如何能做到這一點的PHP的
如果我明白你的要求,你可以做到這一點使用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 < ---約捲曲
示例代碼說明:
$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
祝你好運。
對不起,我沒有說清楚讓我這樣做 – 2010-12-18 19:23:47
我在答案中寫的結構正是你要找的。 – Lockhead 2010-12-18 19:25:27
如果你簡單地解釋代碼,並且有任何檢查只需要有效的網址,而不是增加頁面 – 2010-12-18 19:38:23
因此,您想知道給定頁面中有多少網址,然後隨機選擇一個? – seriousdev 2010-12-18 19:24:04
你是什麼意思你想選擇URL隨機?你的問題不是很具描述性。 – Brad 2010-12-18 19:15:19