php - 简单的 HTML DOM 内存问题

标签 php html mysql csv simple-html-dom

我正在尝试使用 PHP Simple HTML Dom Parser 来解析 SQL 查询结果中的一些信息。但它似乎存在一些巨大的内存问题。我使用 SQL 查询结果创建一个 html 表,然后将 html 表导出到 csv 文件。我对此真的很陌生,所以我的代码不是最有效的。当我的查询结果很小时,csv 文件已成功创建。但是当查询结果很大时,导出的csv文件没有任何sql结果,而是显示:

Fatal error: Call to a member function find() on boolean in /opt/lampp/htdocs/test.php on line 101

这是我的函数,它获取 sqlresult 并创建一个 html 表,然后将其导出到 csv 文件中:

 echo sql_to_html_table($sqlresult, $delim="\n" );

function sql_to_html_table($sqlresult, $delim="\n") {
// starting table
include_once('simple_html_dom.php');
$htmltable =  "<table>" . $delim ;
$counter   = 0 ;
// putting in lines
//while( $row = $sqlresult->mysqli_fetch_assoc()  ){
while($row = mysqli_fetch_assoc($sqlresult)) {
if ( $counter===0 ) {
// table header
$htmltable .=   "<tr>"  . $delim;
foreach ($row as $key => $value ) {
      $htmltable .=   "<th>" . $key . "</th>"  . $delim ;
  }
  $htmltable .=   "</tr>"  . $delim ;
  $counter = 22;
 }
  // table body
  $htmltable .=   "<tr>"  . $delim ;
  foreach ($row as $key => $value ) {
      $htmltable .=   "<td>" . $value . "</td>"  . $delim ;
  }
  $htmltable .=   "</tr>"   . $delim ;
 }
 // closing table

$htmltable .=   "</table>"   . $delim ;
 // return
//return( $htmltable ) ;
$html = str_get_html($htmltable);

header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');

$fp = fopen("php://output", "w");

foreach($html->find('tr') as $element)
{
$td = array();
foreach( $element->find('th') as $row)
{
    $td [] = $row->plaintext;
}
fputcsv($fp, $td);
$td = array();
foreach( $element->find('td') as $row)
{
    $td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
} 

我尝试在 $html = str_get_html($htmltable); 之后抛出异常像这样:

if (!str_get_html($htmltable)) {
throw new exception('exception') ; 
}

当我尝试运行代码时,我的浏览器给出了这个错误:

Fatal error: Uncaught exception 'Exception' with message 'exception' in /opt/lampp/htdocs/test.php:96 Stack trace: #0 /opt/lampp/htdocs/test.php(62): sql_to_html_table(Object(mysqli_result), '\n') #1 {main} thrown in /opt/lampp/htdocs/test.php on line 96

最佳答案

查看 SourceForge 中的 simple_html_dom.php 副本,这听起来像是足够大的 HTML 字符串的预期行为。我看到 str_get_html() 有一个检查,如果字符串的大小大于 MAX_FILE_SIZE,则该检查将导致返回 false。 MAX_FILE_SIZE 定义为:

define('MAX_FILE_SIZE', 600000);

所以看起来 simple_html_dom 无法处理任何大于 600kb 的字符串。由于这是一个内置限制,我想您的选择是尝试更改限制并查看会发生什么或使用不同的库。

或者,您可以完全跳过 HTML 部分。如果您需要出于其他目的生成 HTML,那没问题,但是您没有理由不能通过直接从数据库结果而不是 HTML 构建 CSV 来绕过此问题。

关于php - 简单的 HTML DOM 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054616/

相关文章:

php - 播种 - 具有 3 级关系的 Laravel 模型工厂

html - CSS :hover behaviour on touchscreen devices

php - 使用 PHP DOMDocument 解析脏 html 代码有困难

javascript - 单击跨度时更改主题

html - 元素根据 parent 和 sibling 调整宽度

java - 使用 JSP 的数据库并收到错误

mysql - 连接CGI(C编程)与Mysql时出错

mysql - SELECT INTO MySQL 声明中的多个变量

javascript - $.post jquery result fill more than one field

php - 从 moodialog 中获取特定字段并将值传递给父屏幕