19

我想要做的是在 PHP 系统中包含一个 HTML 文件(不是问题),但由于各种原因,该 HTML 文件也需要单独使用,所以我需要知道如何去除 doctype,html , 如果可能的话,PHP 上下文中的 head 和 body 标记包括。

我不是特别擅长 PHP(doh!),所以我在 php 手册和网络上的搜索并没有让我明白这一点。这意味着非常感谢任何帮助或阅读提示,或两者兼而有之。

4

8 回答 8

23

由于该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();

http://codepad.org/MQVQ3XQP

任何人都希望看到“另一个”,请参阅修订版。

于 2012-06-29T01:07:18.563 回答
14
$site = file_get_contents("http://www.google.com/");

preg_match("/<body[^>]*>(.*?)<\/body>/is", $site, $matches);

echo($matches[1]);
于 2018-01-08T18:45:50.120 回答
6

使用 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);
}
于 2012-06-29T01:21:26.893 回答
3

您可能希望使用 PHP tidy 扩展来修复无效的 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();
于 2014-09-04T13:49:20.917 回答
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
}

如果你想避免规范化,你可以使用这个版本(感谢@Jared Farrish)

于 2012-06-29T01:23:39.893 回答
0

正如miken32 所说

嘿,为什么不回答一个 9 岁的问题?PHP 5.4 版(在提出这个问题 3 年后发布)将options参数添加到 DomDocument::loadHTML(). 有了它,你可以这样做:

$dom = new DomDocument();
$dom->loadHTML($string, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

// do stuff

echo $dom->saveHTML();

我们传递了两个常量:LIBXML_HTML_NODEFDTD表示不添加文档类型定义,并LIBXML_HTML_NOIMPLIED表示不添加隐含元素,如<html>and <body>

于 2021-07-02T05:24:57.973 回答
0

只有一个 DOMDocument 实例且没有循环的解决方案

$d = new DOMDocument();
$d->loadHTML(file_get_contents('/path/to/my.html'));
$body = $d->getElementsByTagName('body')->item(0);
echo $d->saveHTML($body);
于 2019-07-17T09:43:52.990 回答
-1

这可能是一个解决方案。我试过了,效果很好。

function parseHTML(string) {
      var   parser = new DOMParser
     , result = parser.parseFromString(string, "text/html");
      return result.firstChild.lastChild.firstChild;
    }

于 2016-03-14T10:27:07.087 回答