我正在尝试解析一些不在我的服务器上的 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/