2014-01-21 43 views
0

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

我有这样的代码:

$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代码(在重定向之后)。感谢您的帮助

+0

如果没有通过HTTP位置标题进行重定向,那当然没有什么fopen可以自动跟踪,即使它想要。如果JS代码是这里“重定向”的唯一东西,那么您将不得不解析并(伪)执行该JS代码以获取重定向的目标地址。 – CBroe

回答

0

退房这一解决方案从另一个SO后:

Will PHPs fopen follow 301 redirects?

另一种选择是将卷曲而不是使用的fopen,其中有一个选项可以设置,告诉它进行重定向( CURLOPT_FOLLOWLOCATION)。

+0

你可以写它作为评论。它的重复。 – voodoo417

+0

对不起,我只是找到解决办法。这只是因为我忘了发送cookie到我的上下文,所以出现了重定向,因为HTTPS页面没有“识别”我。使用浏览器可以工作,因为它自然发送cookie。不管怎么说,还是要谢谢你 –

1

follow redirects with curl in php

在尽可能短的重复:这不是一个可靠的方式是可行的。

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

我能想到的唯一方法是使用正则表达式找到location.href或location.top,然后遵循这些重定向。但是,再次,有很多方法来重定向页面,你不能期望解析它们!

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');