你不能用strip_tags()
实现这一目标,因为它甫一删除标签。你不想用例如一个空白字符(新行,空格,..)。 你应该用一个正则表达式来调用它,它只是替换所有的标签。
更好的方法将解析提取的页面DOMDocument,以便您可以直接从HTML结构派生结构。 DOM文档
的使用
示例您有下面的示例中的HTML页面:
<!DOCTYPE html>
<html>
<head>
<title>This is my title</title>
</head>
<body>
<table id="someDataHere">
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tr>
<td>Germany</td>
<td>81,779,600</td>
</tr>
<tr>
<td>Belgium</td>
<td>11,007,020</td>
</tr>
<tr>
<td>Netherlands</td>
<td>16,847,007</td>
</tr>
</table>
</body>
</html>
您可以使用DOMDocument
表中获取的条目:
$url = "...";
$dom = new DOMDocument("1.0", "UTF-8");
$dom->loadHTML(file_get_contents($url));
$preparedData = array();
$table = $dom->getElementById("someDataHere");
$tableRows = $table->getElementsByTagName('tr');
foreach ($tableRows as $tableRow)
{
$columns = $tableRow->getElementsByTagName('td');
// skip the header row of the table - it has no <td>, just <th>
if (0 == $columns->length)
{
continue;
}
$preparedData[ $columns->item(0)->nodeValue ] = $columns->item(1)->nodeValue;
}
$preparedData
将现持有以下数据:
Array
(
[Germany] => 81,779,600
[Belgium] => 11,007,020
[Netherlands] => 16,847,007
)
的一些注意事项
- 既然你正在开发一个爬虫(蜘蛛),你是高度依赖于目标网页的HTML结构。每当他们更改模板中的内容时,您可能需要调整抓取工具。
- 这只是一个简单的例子,但它应该清楚,现在如何使用它来产生更高级的结果。
- 由于
DOMDocument
实现了DOM方法,因此您必须通过HTML结构来处理它们提供的可能性。
- 对于非常大的HTML页面
DOMDocument
在内存方面会变得非常昂贵。
您能否提供您从url中检索的原始数据的副本?这将有助于确定如何处理数据。 – 2012-02-22 10:17:05