2014-11-25 55 views
1

过去1小时,我一直在摸它的头。是否有任何可靠的方法从HTML页面提取仅文本PHP从html页面提取所有文本

以及其他任何内容(代码,图像,链接,样式,脚本)。我试图提取html文档正文内的所有文本。

这包括段落,纯文本和表格数据..

到目前为止,我已经尝试simplehtmldom解析器也file_get_contents但他们两人都没有工作。这里是代码:

<?php 

require_once "simple_html_dom.php"; 

function getplaintextintrofromhtml($html) { 

    // Remove the HTML tags 
    $html = strip_tags($html); 

    // Convert HTML entities to single characters 
    $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8'); 

    return $html; 

} 

$html = file_get_contents('http://www.thefreedictionary.com/contempt'); 

echo getplaintextintrofromhtml($html); 
?> 

下面是输出的截图:

https://docs.google.com/file/d/0B-b63LoI1gSfaGhpR0NvdUtlbW8/edit?usp=drivesdk

正如你可以看到它显示的是奇怪的输出甚至没有显示整个页面的文本

+0

http://php.net/manual/en/book.curl.php和用strip_tags() – EL3PHANTEN 2014-11-25 10:42:54

+0

你想要提取什么?其不清楚。最终的输出应该是什么? ''内的内容? – Ghost 2014-11-25 10:48:08

+0

编辑我的问题@Ghost – 2014-11-25 10:49:55

回答

1

我不为什么你认为SimpleHTMLDOM不工作,但你必须要正确地使用它,只是针对身体,然后用->innertext属性:

function getplaintextintrofromhtml($url) { 
    include 'simple_html_dom.php'; 

    $html = file_get_html($url); 
    // point to the body, then get the innertext 
    $data = $html->find('body', 0)->innertext; 
    return $data; 
} 

echo getplaintextintrofromhtml('http://www.thefreedictionary.com/contempt'); 
1

我认为PHP简单HTML DOM解析器是最快最容易的方法 尝试 http://simplehtmldom.sourceforge.net/

features 
A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way! 
Require PHP 5+. 
Supports invalid HTML. 
Find tags on an HTML page with selectors just like jQuery. 
Extract contents from HTML in a single line 
0

Html2Text仅仅是一个好的图书馆为了那个原因。

https://github.com/mtibben/html2text

安装用作曲:

composer require html2text/html2text 

基本用法:

$html = new \Html2Text\Html2Text('Hello, &quot;<b>world</b>&quot;'); 

echo $html->getText(); // Hello, "WORLD"