【问题标题】:php get body from html pagephp从html页面获取正文
【发布时间】:2014-08-16 10:08:02
【问题描述】:

我想从完整的 html 代码中去除一些 html-body 代码。

我使用下面的脚本。

<?php       
    function getbody($filename) {
      $file = file_get_contents($filename);

      $bodystartpattern = ".*<body>";
      $bodyendpattern = "</body>.*";

      $noheader = eregi_replace($bodystartpattern, "", $file);

      $noheader = eregi_replace($bodyendpattern, "", $noheader);

      return $noheader;
    }
    $bodycontent = getbody($_GET['url']);
?>

但在某些情况下,标签&lt;body&gt; 并不存在,但标签可能是&lt;body style="margin:0;"&gt; 或其他东西。谁能告诉我,在这种情况下,通过在 $bodystartpattern 中使用正则表达式来查找开头-body-tag 的关闭->”,找到 body-tag 的解决方案是什么?

【问题讨论】:

  • 旁注:eregi_replace() 自 PHP 5.3.0 起,该函数已被弃用。强烈建议不要依赖此功能。
  • 检查this answer 使用正则表达式解析html...

标签: php html regex


【解决方案1】:

为什么不使用 html 解析器?

function getbody($filename) {
  $file = file_get_contents($filename);

  $dom = new DOMDocument();
  libxml_use_internal_errors(true);
  $dom->loadHTML($file);
  libxml_use_internal_errors(false);
  $bodies = $dom->getElementsByTagName('body');
  assert($bodies->length === 1);
  $body = $bodies->item(0);
  for ($i = 0; $i < $body->children->length; $i++) {
      $body->remove($body->children->item($i));
  }
  $stringbody = $dom->saveHTML($body);
  return $stringbody;
}

DOM loadHTML reference

【讨论】:

  • 我已经复制了你的代码,但现在它什么也没有返回了......有什么想法吗?
  • @GuidoLemmens2 你在里面有没有 php 代码.. 更具体地说是一些 $ ?它可以打破一切。你有错误报告吗?你得到了一些回应吗?
【解决方案2】:

@1nflktd 我已经尝试了下面的代码。

<?php
    header('Content-Type:text/html; charset=UTF-8');

    function getbody($filename) {
        $file = file_get_contents($filename);       
        $dom = new DOMDocument;
        $dom->loadHTML($file);
        $bodies = $dom->getElementsByTagName('body');
        assert($bodies->length === 1);
        $body = $bodies->item(0);
        for ($i = 0; $i < $body->children->length; $i++) {
            $body->remove($body->children->item($i));
        }
        $stringbody = $dom->saveHTML($body);
        return $stringbody;
    }

    $url = "http://www.barcelona.com/";
    $bodycontent = getbody($url);
?>

<html>
<head></head>
<body>
<?php
    echo "BODY ripped from: ".$url."<br/>";
    echo "<textarea rows='40' cols='200' >".$bodycontent."</textarea>";
?>
</body>
</html>

【讨论】:

猜你喜欢
  • 2014-08-21
  • 2015-07-20
  • 2015-11-01
  • 2015-01-09
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多