douaikuai2715 2010-12-18 19:12
浏览 77
已采纳

从网站获取随机网址

I want to search number of links or URL on http://public-domain-content.com and store them in an array and then just randomly select any one from array and just display or echo

How can i do that in php

  • 写回答

1条回答 默认 最新

  • duanqun9740 2010-12-18 19:20
    关注

    If I understood what you're asking, you can achieve this using file_get_contents();

    After using file_get_contents($url), which gives you a string, you can loop through the result string searching for spaces to tell the words apart. Count the number of words, and store the words in an array accordingly. Then just choose a random element from the array using array_rand()

    However, sometimes there are security problems with file_get_contents(). You can override this using the following function:

    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 <--- Explanation about curl

    Example code:

    $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
    

    There is also a more extended version to checking URLs, which you can explore here:

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

    Good luck.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入