php如何抓取网页上的数据并将数据存储到数据库
时间: 2024-06-09 22:08:39 浏览: 9
可以使用PHP的curl库抓取网页上的数据,然后使用MySQL或其他数据库的API将数据存储到数据库中。以下是一个简单的示例:
```php
// 设置 curl
$url = 'http://example.com/data.html';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 获取数据
$data = curl_exec($ch);
curl_close($ch);
// 解析数据
$dom = new DOMDocument();
$dom->loadHTML($data);
$tables = $dom->getElementsByTagName('table');
$table = $tables->item(0);
$rows = $table->getElementsByTagName('tr');
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
$name = $cells->item(0)->textContent;
$age = $cells->item(1)->textContent;
$city = $cells->item(2)->textContent;
// 存储数据到数据库
$db = new mysqli('localhost', 'username', 'password', 'database_name');
$query = "INSERT INTO people (name, age, city) VALUES ('$name', '$age', '$city')";
$db->query($query);
$db->close();
}
```
需要注意的是,在实际应用中需要对抓取的数据进行过滤和验证,以防止恶意数据的注入和误操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)