使用fopen打开HTML文件(重定向)

时间:2014-01-21 21:00:41

标签: php file fopen

我想用PHP打开HTTPS文件,但是这个页面重定向到另一个页面,因此fopen函数不会解析我想要的页面。

我有这段代码:

$url = 'myHTMLPageWithParameters';

$file = file($url);

// test
var_dump($file);

结果:

array (size=12)
  0 => string '<html>
' (length=7)
  1 => string '<head>
' (length=7)
  2 => string '<script language="javascript">
' (length=31)
  3 => string 'function setTop(){top.location="/index.htm"}
' (length=45)
  4 => string '</script>
' (length=10)
  5 => string '<title>...</title>
' (length=19)
  6 => string '</head>
' (length=8)
  7 => string '
' (length=1)
  8 => string '<body onLoad="setTop()">
' (length=25)
  9 => string '</body>
' (length=8)
  10 => string '
' (length=1)
  11 => string '</html>
' (length=8)

当我在HTML浏览器中显示“myHTMLPageWithParameters”时,我会在重定向后看到正确的页面。我只是想找到一种方法来捕获第二页的HTML代码(在重定向之后)。谢谢你的帮助

3 个答案:

答案 0 :(得分:1)

follow redirects with curl in php

可能重复

简而言之:它无法以可靠的方式行事。

这不是服务器完成的重定向,而是获取您请求的页面。然后,该页面重定向到另一个页面,但使用javascript。 Javascript由浏览器解释,而不是由php,curl或任何其他库解释。

我能想到的唯一方法是,使用正则表达式查找location.href或location.top,然后按照这些重定向进行操作。但是,有很多方法可以重定向页面,你不能期望解析它们全部!

答案 1 :(得分:0)

从其他SO帖子中查看此解决方案:

Will PHPs fopen follow 301 redirects?

另一种选择是使用curl而不是fopen,它有一个可以设置的选项,告诉它遵循重定向(CURLOPT_FOLLOWLOCATION)。

答案 2 :(得分:0)

您可以使用FOLLOW_LOCATION;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "myHTMLPageWithParameters");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$html_response = curl_exec($ch);

// We get the content
$html = str_get_html($html_response);

// Get #result div for example
$content = $html->find('#result');
相关问题