PHP parsing invalid html

浪尽此生 提交于 2019-12-28 06:46:11

问题


i'm trying to parse some html that is not on my server

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

but php returns an error something like ID his_id already defined in http://www.some-site.org/page.aspx, line: 33. I think that is because DOMDocument is dealing with invalid html. So, how can i parse it even though is invalid?


回答1:


You should run HTML Tidy on it to clean it up before parsing it.

$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);

See this list of options.




回答2:


Have a look at: libxml_use_internal_errors()

http://php.net/libxml_use_internal_errors




回答3:


Reading the docs, I see a $dom->strictErrorChecking that defaults to TRUE. What happens if you set $dom->strictErrorChecking = false?



来源:https://stackoverflow.com/questions/2702799/php-parsing-invalid-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!