1

我正在使用最新的 PHP。我想解析 HTML 页面以获取数据。

HTML:

<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>

<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>

<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>

<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>

PHP代码:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.test.com/mypage.html');  
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);


$pattern = '/<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="1" cellpadding="0" cellspacing="0">[^~]</table>/';
preg_match_all($pattern, $result, $matches);
print_r($matches);

?>

我无法获得所有表格。当我使用简单的 $pattern='/table/'; ,它给了我确切的结果。如何创建一种模式以在一个数组位置获取整个表?

4

4 回答 4

6

使用正则表达式解析 HTML 充其量是一种痛苦,因为 HTML 不规则,我建议您使用Simple HTML DOM

于 2009-12-14T17:01:37.747 回答
3

您无法使用 regex 解析 [X]HTML,但您可以尝试:

$pattern = '#<table(?:.*?)>(.*?)</table>#';

如果有嵌套表,这将不起作用。

于 2009-12-14T17:03:29.243 回答
2

请看一下这个答案。它描述了在 PHP 中使用 HTML 解析器,这是您想要做的。

于 2009-12-14T17:04:30.470 回答
1

或者只是使用 DOM 类 php 提供。我认为它可以和简单的 html dom 一样,但速度更快(不要误会我的意思,我真的很喜欢 Simple Html DOM,但是对于几十行的文件来说它很慢)

于 2009-12-14T17:03:14.000 回答