file_get_contents() 函数加载与浏览器不同的页面

file_get_contents() function loads different page compared to broswer

我正在尝试查找特定页面的下一页 link(我在这里将该特定页面称为 current page)。我正在使用的程序中的 current page

http://en.wikipedia.org/wiki/Category:1980_births

我从 current page 中提取的 next page link 是下面的

http://en.wikipedia.org/w/index.php?title=Category:1980_births&pagefrom=Alexis%2C+Toya%0AToya+Alexis#mw-pages

但是,当 file_get_contents() 函数加载 next page link 时,它正在获取 current page 内容 ,

密码是

<?php

$string = file_get_contents("http://en.wikipedia.org/wiki/Category:1980_births");  //Getting contents of current page , 
preg_match_all("/\(previous page\) \(<a href=\"(.*)\" title/",  $string,$matches);    // extracting the next_page_link from the current page contents

foreach ($matches[1] as $match) {
break;
}

$next_page_link = $match;  
$next_page_link =  "http://en.wikipedia.org" . $next_page_link; //the next_link will have only the path , does't contain the domain name ,,, so i am adding the domain name here, this does't make any impact on the problem statement

$string1 = file_get_contents($next_page_link);
echo $next_page_link;
echo $string1;

?>

根据代码 string1 应该有 next_page_link's 内容,但它只是获取 current page 的内容。

在原始网站的源代码中,链接带有实体编码的符号(参见 Do I encode ampersands in <a href…>?)。当您单击锚点时,浏览器会正常解码它们,但您的抓取代码不会。比较

http://en.wikipedia.org/ ... &amp;pagefrom=Alexis%2C+Toya%0AToya+Alexis#mw-pages

对比

http://en.wikipedia.org ... &pagefrom=Alexis%2C+Toya%0AToya+Alexis#mw-pages

这个格式错误的查询字符串实际上是您传递给 file_get_contents 的内容。您可以像这样将它们转换回常规的符号:

// $next_page_link = $match; 
$next_page_link = html_entity_decode($match);