如何用php抓取网页数据
使用PHP抓取网页数据可使用cURL库还是file_get_contents函数。以下是两种方法的示例:
// 创建cURL资源
$ch = curl_init();
// 设置URL和其他cURL选项
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 履行cURL要求并获得响应
$response = curl_exec($ch);
// 关闭cURL资源
curl_close($ch);
// 输出响应内容
echo $response;
// 读取网页内容
$response = file_get_contents("http://example.com");
// 输出响应内容
echo $response;
不管使用哪一种方法,都可以通过解析响应内容来提取所需的网页数据。你可使用字符串函数、正则表达式还是PHP提供的DOM解析器来处理响应内容。
TOP