使用 file_get_contents 将 html 表解析为 php 数组

Posted

技术标签:

【中文标题】使用 file_get_contents 将 html 表解析为 php 数组【英文标题】:Parse html table using file_get_contents to php array 【发布时间】:2012-01-07 09:34:43 【问题描述】:

我正在尝试将 here 显示的表解析为多维 php 数组。我正在使用以下代码,但由于某种原因它返回一个空数组。在网上搜索后,我找到了this site,这是我从中获得 parseTable() 函数的地方。通过阅读该网站上的 cmets,我发现该功能运行良好。所以我假设我从 file_get_contents() 获取 html 代码的方式有问题。对我做错了什么有什么想法吗?

<?php

$data = file_get_contents('http://flow935.com/playlist/flowhis.HTM');

function parseTable($html)

  // Find the table
  preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);

  // Get title for each row
  preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
  $row_headers = $matches[1];

  // Iterate each row
  preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);

  $table = array();

  foreach($matches[1] as $row_html)
  
    preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
    $row = array();
    for($i=0; $i<count($td_matches[1]); $i++)
    
      $td = strip_tags(html_entity_decode($td_matches[1][$i]));
      $row[$row_headers[$i]] = $td;
    

    if(count($row) > 0)
      $table[] = $row;
  
  return $table;


$output = parseTable($data);

print_r($output);

?>

我希望我的输出数组看起来像这样:

1 --> 上午 11:33 --> 开发 --> 在黑暗中 2 --> 上午 11:29 --> 律韦恩 --> 她会的 3 --> 上午 11:26 --> 卡迪纳尔OFFISHALL --> NUMBA 1(潮位高)

【问题讨论】:

-1 表示缺乏努力。隔离您的问题,而不是基本上发布一大段代码并要求人们找出问题所在并进行修复。 【参考方案1】:

不要用正则表达式解析 HTML! 相反,让 HTML 解析器库为您担心标记的结构。

我建议您查看 Simple HTML DOM (http://simplehtmldom.sourceforge.net/)。它是一个专门为帮助解决 PHP 中的此类 Web 抓取问题而编写的库。通过使用这样的库,您可以用更少的代码行编写您的抓取,而不必担心创建有效的正则表达式。

原则上,使用 Simple HTML DOM,您只需编写如下内容:

$html = file_get_html('http://flow935.com/playlist/flowhis.HTM');
foreach($html->find('tr') as $row) 
   // Parse table row here

这可以扩展为以某种格式捕获您的数据,例如创建一组艺术家和相应的标题:

<?php
require('simple_html_dom.php');

$table = array();

$html = file_get_html('http://flow935.com/playlist/flowhis.HTM');
foreach($html->find('tr') as $row) 
    $time = $row->find('td',0)->plaintext;
    $artist = $row->find('td',1)->plaintext;
    $title = $row->find('td',2)->plaintext;

    $table[$artist][$title] = true;


echo '<pre>';
print_r($table);
echo '</pre>';

?>

我们可以看到,这段代码也可以(简单地)更改为以任何其他方式重新格式化数据。

【讨论】:

效果很好。但我需要制作一个多维数组,如原始问题底部所示。 您是否查看了示例“Scraping Slashdot!”从 simplehtmldom 网站?据我了解,它回答了这个问题。 好的,我又添加了一个例子,但我就到此为止了。剩下的留给你自己解决。 是的,我想通了。感谢您提供更多示例。 使用 simplehtmldom 代替 rexexps 很有趣,不是吗? :)【参考方案2】:

我尝试了 simple_html_dom,但在较大的文件和重复调用函数时,我在 php 5.3 (GAH) 上得到了 zend_mm_heap_corrupted。我也尝试过 preg_match_all (但这在较大的 html 文件 (5000) 行上失败了,而我的 HTML 表只有大约 400 行。

我正在使用它,它的工作速度很快,不会出现错误。

$dom = new DOMDocument();  

//load the html  
$html = $dom->loadHTMLFile("htmltable.html");  

  //discard white space   
$dom->preserveWhiteSpace = false;   

  //the table by its tag name  
$tables = $dom->getElementsByTagName('table');   


    //get all rows from the table  
$rows = $tables->item(0)->getElementsByTagName('tr');   
  // get each column by tag name  
$cols = $rows->item(0)->getElementsByTagName('th');   
$row_headers = NULL;
foreach ($cols as $node) 
    //print $node->nodeValue."\n";   
    $row_headers[] = $node->nodeValue;
   

$table = array();
  //get all rows from the table  
$rows = $tables->item(0)->getElementsByTagName('tr');   
foreach ($rows as $row)   
   
   // get each column by tag name  
    $cols = $row->getElementsByTagName('td');   
    $row = array();
    $i=0;
    foreach ($cols as $node) 
        # code...
        //print $node->nodeValue."\n";   
        if($row_headers==NULL)
            $row[] = $node->nodeValue;
        else
            $row[$row_headers[$i]] = $node->nodeValue;
        $i++;
       
    $table[] = $row;
   

var_dump($table);

这段代码对我很有效。 原始代码示例在这里。

http://techgossipz.blogspot.co.nz/2010/02/how-to-parse-html-using-dom-with-php.html

【讨论】:

你应该做 array_shift($table) 因为第一个元素将是 [0] => array(0) 为空。这是因为您在 $rows 中获得了所有 tr 标签,包括带有 th 标签的标签。我会建议编辑。 我在 PHP 5.6.31 中使用 DOM,但发现 $rows = $tables-&gt;item(0)-&gt;getElementsByTagName('tr') 的结果不包含任何后续 $cols = $row-&gt;getElementsByTagName('td')&lt;td&gt; 标签。知道为什么我第一次调用 getElementsByTagName() 似乎是在剥离 HTML 标签吗?

以上是关于使用 file_get_contents 将 html 表解析为 php 数组的主要内容,如果未能解决你的问题,请参考以下文章

目标 C:序列化/归档问题

HT for Web框架使用 费用多少?

Matlab中如何修改x轴为汉字或字母?Matlab中如何将x轴设定为字母或者其他?

[译]C语言实现一个简易的Hash table

HT for Web基础动画介绍

HT for Web基础动画介绍