PHP解析无效的html

kmu*_*nky 9 php html-parsing domdocument

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

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

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

cle*_*tus 7

在解析之前,您应该在其上运行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);
Run Code Online (Sandbox Code Playgroud)

请参阅此选项列表.