如何使用 PHP 解析 HTML 表格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8816194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse HTML table using PHP?
提问by isiaatz
Possible Duplicate:
How to parse and process HTML with PHP?
可能的重复:
如何使用 PHP 解析和处理 HTML?
I need to fetch the second column of the given HTML table using PHP. How can I do it?
我需要使用 PHP 获取给定 HTML 表的第二列。我该怎么做?
References:
参考:
Table to be parsed: http://bit.ly/Ak2xay
要解析的表:http: //bit.ly/Ak2xay
HTML code of this table: http://bit.ly/ACdLMn
此表的 HTML 代码:http: //bit.ly/ACdLMn
回答by codersofthedark
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.
对于整洁的 HTML 代码,解析方法之一可以是 DOM。DOM 将您的 HTML 代码划分为对象,然后允许您调用所需的对象及其值/标签名称等。
The official documentation of PHP HTML DOM parsing is available at http://php.net/manual/en/book.dom.php
PHP HTML DOM 解析的官方文档可在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:
为了在 DOM 实现之后找到给定表的第二列的值,可以完成:
<?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.
参考:自定义如何解析此表并从中提取数据?以满足这个问题的需求。
回答by Geoffrey
This may be of use to you, there are even examples to get you started.
这可能对您有用,甚至还有一些示例可以帮助您入门。
回答by Clark T.
Using phpQuery http://code.google.com/p/phpquery/you could do
使用 phpQuery http://code.google.com/p/phpquery/你可以做
$file = LINK OR NAME OF YOUR FILE
phpQuery::newDocumentFile($file);
$data = pq('UNIQUE COLUMN ID OR CLASS AS YOU WOULD FOR CSS ex: .class #id')->html();
echo $data.
回答by jeroen
Maybe have a look at phpQuery: http://code.google.com/p/phpquery/?
I haven't used it myself so I'm not 100% sure it does what you want, but since it is a server-side implementation of jQuery to select from the DOM, using CSS selectors, I think it could be useful in your case.
也许看看 phpQuery: http://code.google.com/p/phpquery/?
我自己没有使用过它,所以我不能 100% 确定它可以满足您的需求,但是由于它是 jQuery 的服务器端实现,可以使用 CSS 选择器从 DOM 中进行选择,因此我认为它可能对您有用案件。