php 循环抓取网页内容( 使用file_get_contents获取页面内容,如何实现? )
优采云 发布时间: 2021-09-13 02:10php 循环抓取网页内容(
使用file_get_contents获取页面内容,如何实现?
)
php file_get_contents() 请求页面时获取cookie值
时间:2016-09-01
需求是这样的。使用file_get_contents请求页面并获取cookie值,然后使用该cookie值再次获取页面内容。如何实现?具体代码见下例。
使用file_get_contents获取页面内容后,我们可以使用$http_response_header获取响应头信息。响应头信息一般包括 cookie 变量的值。具体实现代码如下:
file_get_contents('http://example.org');
$cookies = array();
foreach ($http_response_header as $hdr) {
if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
parse_str($matches[1], $tmp);
$cookies += $tmp;
}
}
/* http://www.manongjc.com/article/1429.html */
print_r($cookies);
可以使用 stream_get_meta_data() 实现异常方法:
if (false !== ($f = fopen('http://www.example.org', 'r'))) {
$meta = stream_get_meta_data($f);
$headers = $meta['wrapper_data'];
$contents = stream_get_contents($f);
fclose($f);
}
// $headers now contains the same array as $http_response_header