以下是一个使用PHP抓取网页内容的实例,包括HTML代码和PHP代码。我们将使用PHP的`file_get_contents`函数来获取网页内容,并使用`DOMDocument`和`DOMXPath`来解析HTML内容。
HTML表格示例
```html

| 名称 | 价格 | 库存 |
|---|---|---|
| 产品1 | $10 | 50 |
| 产品2 | $20 | 30 |
| 产品3 | $30 | 20 |
```
PHP代码示例
```php
// 要抓取的网页内容
$htmlContent = file_get_contents('http://example.com'); // 替换为实际的网址
// 创建DOMDocument对象
$dom = new DOMDocument();
// 加载HTML内容
@$dom->loadHTML($htmlContent); // 使用@来抑制警告,因为HTML可能不规范
// 创建DOMXPath对象
$xpath = new DOMXPath($dom);
// 查询表格
$tables = $xpath->query('//table');
// 遍历表格
foreach ($tables as $table) {
// 获取表头
$headers = [];
foreach ($table->getElementsByTagName('th') as $th) {
$headers[] = $th->nodeValue;
}
// 获取表格数据
$rows = [];
foreach ($table->getElementsByTagName('tr') as $tr) {
$cells = [];
foreach ($tr->getElementsByTagName('td') as $td) {
$cells[] = $td->nodeValue;
}
$rows[] = $cells;
}
// 输出表格数据
echo "









