温馨提示×

如何使用Fopen打开URL

小樊
82
2024-06-17 18:19:54
栏目: 编程语言

在使用fopen打开URL时,需要使用stream_context_create函数来创建一个流上下文(stream context),并将其作为fopen函数的第三个参数传入。下面是一个简单的示例:

$url = 'https://www.example.com';

$options = [
    'http' => [
        'method' => 'GET',
        'header' => 'User-Agent: MyScript',
    ],
];

$context = stream_context_create($options);
$handle = fopen($url, 'r', false, $context);

if ($handle) {
    while (($data = fgets($handle)) !== false) {
        echo $data;
    }
    
    fclose($handle);
} else {
    echo 'Failed to open URL';
}

在这个示例中,我们创建了一个stream_context对象,并将其包含了请求头信息(User-Agent)作为选项传入。然后使用fopen函数打开URL,并读取其内容输出。最后记得关闭文件句柄。

0