【问题标题】:Php extract html body content along with html tags not only plain textphp 提取 html 正文内容以及 html 标签,而不仅仅是纯文本
【发布时间】:2016-10-31 13:00:09
【问题描述】:

我是 php 新手。我正在尝试使用 php 从 html 中提取整个 body 标记。

这里是我的示例 html:

<html>
<body >
<p>
  Example html content
</p>
</body>
</html>

我只想从 html 内容中提取以下内容:

<p>
  Example html content
</p>

使用以下我尝试解决,但它只输出没有 html 标签的字符串:

 $dom = new domDocument;
 $dom->loadHTML("<html><body><p>Example html content</p></body></html>");
 $body = $dom->getElementsByTagName('body')->item(0);
 var_dump($body->textContent); //output:Example html content

请帮我解决这个问题。

【问题讨论】:

  • 使用$dom-&gt;saveHTML($body)

标签: javascript php jquery html


【解决方案1】:

更新您的代码如下:

   $dom = new domDocument;
   $dom->loadHTML("<html><body><p>Example html content</p></body></html>");
   $body = $dom->getElementsByTagName('body')->item(0);
   var_dump($dom->savehtml($body));

输出应与html标签一起:

string(26) "<p>Hello!</p>"

【讨论】:

    【解决方案2】:

    您应该改用saveHTML()

    echo $body->saveHTML();
    

    将按照您的预期输出 HTML。

    【讨论】:

      【解决方案3】:

      我不喜欢php原生dom,尽量用简单的html dom,简单又快速。从https://sourceforge.net/projects/simplehtmldom/下载

      include 'simple_html_dom.php';
      $html = new simple_html_dom();
      $html = file_get_html("<html><body><p>Example html content</p></body></html>");
      $data = $html->find('body',0);
      

      $data 包含所有正文元素。

      【讨论】:

        【解决方案4】:

        使用这个

         $data = "<html><body><p>Example html content</p></body></html>";
         preg_match( '/<body>(.*?)<\/body>/', $data, $match );
         print_r($match[1]);
        

        【讨论】:

        • 我的天啊,当你正则表达式爱好者明白时,不要使用正则表达式来抓取 html 数据。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        • 2017-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-06
        相关资源
        最近更新 更多