问题描述
我需要使用PHP获取给定HTML表格的第二列。我可以怎么做?
参考文献:
要解析的表格:
此表的HTML代码:
对于整洁的HTML代码,其中一种解析方法可以是DOM。 DOM将HTML代码划分为对象,然后允许您调用所需的对象及其值/标签名称等。
PHP HTML DOM解析的官方文档可在以匹配此问题的需求。
I need to fetch the second column of the given HTML table using PHP. How can I do it?
References:
Table to be parsed: http://bit.ly/Ak2xay
HTML code of this table: http://bit.ly/ACdLMn
For tidy HTML codes, one of the parsing approach can be DOM. DOM divides your HTML code into objects and then allows you to call the desired object and its values/tag name etc.
The official documentation of PHP HTML DOM parsing is available at http://php.net/manual/en/book.dom.php
For finding the values of second coloumn for the given table following DOM implementation can be done:
<?php
$data = file_get_contents('http://mytemporalbucket.s3.amazonaws.com/code.txt');
$dom = new domDocument;
@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(1)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
echo $cols[2];
}
?>
Reference: Customized the code provided at How to parse this table and extract data from it? to match this question's demand.
这篇关于如何使用PHP解析HTML表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!