7 个答案:
答案 0 :(得分:16)
由于substr()方法对于某些人来说似乎太多了,所以这是一个DOM解析器方法:
$d = new DOMDocument;
$mock = new DOMDocument;
$d->loadHTML(file_get_contents('/path/to/my.html'));
$body = $d->getElementsByTagName('body')->item(0);
foreach ($body->childNodes as $child){
$mock->appendChild($mock->importNode($child, true));
}
echo $mock->saveHTML();
任何人都希望看到“其他人”,请参阅修订版。
答案 1 :(得分:5)
使用DOMDocument来保存您需要的内容而不是删除您不需要的内容(PHP> = 5.3.6)
$d = new DOMDocument;
$d->loadHTMLFile($fileLocation);
$body = $d->getElementsByTagName('body')->item(0);
// perform innerhtml on $body by enumerating child nodes
// and saving them individually
foreach ($body->childNodes as $childNode) {
echo $d->saveHTML($childNode);
}
答案 2 :(得分:3)
$site = file_get_contents("http://www.google.com/");
preg_match("/
]*>(.*?)/is", $site, $matches);echo($matches[1]);
答案 3 :(得分:2)
您可能希望使用PHP整理扩展来修复无效的XHTML结构(在这种情况下DOMDocument加载崩溃)并且还仅提取正文:
$tidy = new tidy();
$htmlBody = $tidy->repairString($html, array(
'output-xhtml' => true,
'show-body-only' => true,
), 'utf8');
然后将提取的主体加载到DOMDocument:
$xml = new DOMDocument();
$xml->loadHTML($htmlBody);
然后遍历,提取,移动XML节点等。并保存:
$output = $xml->saveXML();
答案 4 :(得分:2)
使用DOM解析器。这没有经过测试,但应该做你想做的事情
$domDoc = new DOMDocument();
$domDoc.loadHTMLFile('/path/to/file');
$body = $domDoc->GetElementsByTagName('body')->item(0);
foreach ($body->childNodes as $child){
echo $child->C14N(); //Note this cannonicalizes the representation of the node, but that's not necessarily a bad thing
}
如果你想避免使用cannonicalization,你可以使用this version(感谢@Jared Farrish)
答案 5 :(得分:0)
仅具有一个DOMDocument实例且没有循环的解决方案
$d = new DOMDocument();
$d->loadHTML(file_get_contents('/path/to/my.html'));
$body = $d->getElementsByTagName('body')->item(0);
echo $d->saveHTML($body);
答案 6 :(得分:-1)
这可能是一个解决方案。我试过了,它工作正常。
function parseHTML(string) {
var parser = new DOMParser
, result = parser.parseFromString(string, "text/html");
return result.firstChild.lastChild.firstChild;
}