2016-04-16 44 views
0

我的功能:如何在PHP中的函數外部使用變量?

function raspislinks($url) 
{ 
    $chs = curl_init($url); 
    curl_setopt($chs, CURLOPT_URL, $url); 
    curl_setopt($chs, CURLOPT_COOKIEFILE, 'cookies.txt'); //Подставляем куки раз 
    curl_setopt($chs, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($chs, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36 OPR/29.0.1795.60"); 
    curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, 0); // не проверять SSL сертификат 
    curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, 0); // не проверять Host SSL сертификата 
    curl_setopt($chs, CURLOPT_COOKIEJAR, 'cookies.txt'); //Подставляем куки два 
    $htmll = curl_exec($chs); 
    $pos = strpos($htmll, '<strong><em><font color="green"> <h1>'); 
    $htmll = substr($htmll, $pos); 
    $pos = strpos($htmll, '<!--    </main>-->'); 
    $htmll = substr($htmll, 0, $pos); 
    $htmll = end(explode('<strong><em><font color="green"> <h1>', $htmll)); 
    $htmll = str_replace('<a href ="', '<a href ="https://nfbgu.ru/timetable/fulltime/', $htmll); 
    $GLOBALS['urls']; 
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/", $htmll, $urls); 
    curl_close($chs); 
} 

我如何使用一個變量$網址以外的功能?它是數組。 「return $ urls」不工作,或者我做錯了什麼。請幫幫我。

+0

'return $ urls' should work。發佈無法使用的完整代碼。 – FuzzyTree

回答

1

當您在函數中將值加載到$GLOBALS['urls'];中時,您可以在此函數之外的代碼中使用$urls

$GLOBALS陣列保存每個在全球範圍內都有效的變量之一次數,所以一旦$GLOBALS['urls'];設定該值也可以作爲$urls

引用的值一樣

function raspislinks($url) { 

... 

    //$GLOBALS['urls']; 
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/", 
         $htmll, 
         $GLOBALS['urls'] 
        ); 

} 

raspislinks('google.com'); 
foreach ($urls as $url) { 

} 

一種更簡單的方式將數據放在一個簡單的varibale中,並從函數中返回它

function raspislinks($url) { 

... 

    //$GLOBALS['urls']; 
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/", 
         $htmll, 
         $t 
        ); 
    return $t; 
} 

$urls = raspislinks('google.com'); 
foreach ($urls as $url) { 

} 
相關問題