2014-03-31 49 views
0

我正在寻找URL重定向到的位置,目前我正在使用file_get_contents()获取网页信息,但有些页面正在返回301/302标题状态,我想使用函数来查找页面重定向到的url;找到URL重定向到的位置

function page_info($url) { 
$fp = file_get_contents($url); 
$title = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches); 
$h1 = preg_match("/<h1>(.*)<\/h1>/siU", $fp, $h1_matches); 
$h2 = preg_match("/<h2>(.*)<\/h2>/siU", $fp, $h2_matches); 
$meta_desc = get_meta_tags($url); 
$data = array("title"=>trim(preg_replace('/\s+/', ' ', $title_matches[1])), "metadesc" => $meta_desc['description'],"h1"=>trim(preg_replace('/\s+/', ' ', $h1_matches[1])), "h2"=>trim(preg_replace('/\s+/', ' ', $h2_matches[1]))); 
return $data; 
} 

有什么办法,只是找出重定向的URL,这样我就可以运行在正确的网址,page_info()函数?

+0

可能重复[如何获得由卷曲获取最后的网址是什么?(http://stackoverflow.com/questions/ 10637493 /如何获得最后一个url-curl-by-curl) –

+0

对于'file_get_contents()',AFAIK是不可能的。改用cURL。 –

+0

用正则表达式解析HTML? [让人惊讶](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)。也许有[更好的方法](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php)? – tadman

回答

2

您需要使用php curl库。您可以将其设置为遵循重定向,然后使用getinfo方法找到我们需要的位置。

$curl = curl_init('http://example.org/someredirect'); 
curl_setopt($curl, CURLOPT_POSTFIELDS, "foo"); 
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($curl, CURLOPT_POST, true); 

curl_exec($curl); 

if(!curl_errno($curl)) 
{ 
    $info = curl_getinfo($curl); 
} 

可以传递第二参数的curl_getinfo方法来获得更具体的信息