html - Php Error in_array() null given -
i followed tutorial on making web crawler app. pulls links page , follows them. have problem pushing foreach loop of links global variable. keep getting error says second variable in in_array should array set to. there there guys might see bugging code?
error:
in_array() expects parameter 2 array, null given
html:
<?php $to_crawl = "http://thechive.com/"; $c = array(); function get_links($url){ global $c; $input = file_get_contents($url); $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; preg_match_all("/$regexp/siu", $input, $matches); $l = $matches[2]; $base_url = parse_url($url, php_url_host); foreach($l $link){ if(strpos($link, '#')){ $link = substr($link, 0, strpos($link, '#')); } if(substr($link, 0, 1) == "."){ $link = substr($link, 1); } if(substr($link, 0, 7) == "http://"){ $link = $link; } elseif(substr($link, 0, 8) == "https://"){ $link = $link; } elseif(substr($link, 0, 2) == "//"){ $link = substr($link, 2); } elseif(substr($link, 0, 1) == "#"){ $link = $url; } elseif(substr($link, 0, 7) == "mailto:"){ $link = "[".$link."]"; } else{ if(substr($link, 0,1) != "/"){ $link = $base_url."/".$link; } else{ $link = $base_url.$link; } } if(substr($link, 0, 7) != "http://" && substr($link, 0, 8) != "https://" && substr($link, 0, 1) != "["){ if(substr($link, 0 , 8) == "https://"){ $link = "https://".$link; } else{ $link= "http://".$link; } } if (!in_array($link, $c)){ array_push($c, $link); } } } get_links($to_crawl); foreach($c $page){ get_links($page); } foreach($c $page){ echo $page."<br/ >"; } ?>
trying make "global" $c @ each iteration bad design. should avoid "global" when it's possible.
here see 2 choices :
1/ pass array reference (search google that) in parameter of "get_links" function. allow fill array function.
exemple :
function getlinks($url, &$links){ //do stuff find links //then add each link array $links[] = $onelink; } $alllinks = array(); getlinks("thefirsturl.com", $alllinks); //call getlinks many want //then array contain links print_r($alllinks);
or 2/ make "get_links" return array of links, , concatenate bigger 1 store links.
function getlinks($url){ $links = array(); //do stuff find links //then add each link array $links[] = $onelink; return $links; } $alllinks = array(); $alllinks += getlinks("thefirsturl.com"); //call getlinks many want. note concatenation operator += print_r($alllinks);
Comments
Post a Comment