PHP解析无效的html

标签 php html-parsing domdocument

我正在尝试解析一些不在我的服务器上的 html

    $dom = new DOMDocument();
    $dom->loadHTMLfile("http://www.some-site.org/page.aspx");      
    echo    $dom->getElementById('his_id')->item(0);

但是 php 返回一个错误,类似于 ID his_id already defined in http://www.some-site.org/page.aspx, line: 33。我认为这是因为 DOMDocument 正在处理无效的 html。那么,即使它无效,我该如何解析它呢?

最佳答案

你应该运行 HTML Tidy在解析之前对其进行清理。

$html = file_get_contents('http://www.some-site.org/page.aspx');
$config = array(
  'clean' => 'yes',
  'output-html' => 'yes',
);
$tidy = tidy_parse_string($html, $config, 'utf8');
$tidy->cleanRepair();
$dom = new DOMDocument;
$dom->loadHTML($tidy);

查看此 list of options .

关于PHP解析无效的html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2702799/

相关文章:

java - JSoup 解析带有未闭合标签的无效 HTML

PHP XML 库不返回 XPath 结果

PHP 返回带有名称而不是 ID 的元素

PHP DomDocument - getElementByID(部分匹配)如何?

PHP 递归 : Flatten Tree, 保留元数据

php - 如果数字与框相同,则更改其颜色

css - 从 html 页面中提取类/id

perl - 如何在单独的行上打印 HTML::Treebuilder 节点的文本内容?

php - 如何将字符串缩短一定数量的字符?

php - file_get_contents 大文件上传