我正在使用php,我想以更快的方式从url获取内容。
下面是我使用的代码:
代码:(1)
<?php
$content = file_get_contents('http://www.filehippo.com');
echo $content;
?>
这里有许多其他的方法来读取文件,如fopen()
, readfile()
等。但我认为file_get_contents()
比这些方法更快。
在我上面的代码中,当你执行它时,你会看到它给了这个网站的所有东西,甚至图像和广告。我想只计划html文本,没有css样式,图像和广告。我怎么能得到这个。
看这个来理解。
代码:(2)
<?php
$content = file_get_contents('http://www.filehippo.com');
// do something to remove css-style, images and ads.
// return the plain html text in $mod_content.
echo $mod_content;
?>
如果我像上面那样做,那么我就走错了路,因为我已经在变量$content
中获得了完整的内容,然后修改它。
这里可以是任何函数方法或任何其他直接从url获得纯html文本。
下面的代码只是为了理解而写的,这不是php的原始代码。理想代码: (3);
<?php
$plain_content = get_plain_html('http://www.filehippo.com');
echo $plain_content; // no css-style, images and ads.
?>
如果我能得到这个函数,它将比其他函数快得多。这是可能的吗?
谢谢。
试试这个。
$content = file_get_contents('http://www.filehippo.com');
$this->html = $content;
$this->process();
function process(){
// header
$this->_replace('/.*<head>/ism', "<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE html PUBLIC '-//WAPFORUM//DTD XHTML Mobile 1.0//EN' 'http://www.wapforum.org/DTD/xhtml-mobile10.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head>");
// title
$this->_replace('/<head>.*?(<title>.*<'/title>).*?<'/head>/ism', '<head>$1</head>');
// strip out divs with little content
$this->_stripContentlessDivs();
// divs/p
$this->_replace('/<div[^>]*>/ism', '') ;
$this->_replace('/<'/div>/ism','<br/><br/>');
$this->_replace('/<p[^>]*>/ism','');
$this->_replace('/<'/p>/ism', '<br/>') ;
// h tags
$this->_replace('/<h[1-5][^>]*>(.*?)<'/h[1-5]>/ism', '<br/><b>$1</b><br/><br/>') ;
// remove align/height/width/style/rel/id/class tags
$this->_replace('/'salign=(''?'"?).*?''1/ism','');
$this->_replace('/'sheight=(''?'"?).*?''1/ism','');
$this->_replace('/'swidth=(''?'"?).*?''1/ism','');
$this->_replace('/'sstyle=(''?'"?).*?''1/ism','');
$this->_replace('/'srel=(''?'"?).*?''1/ism','');
$this->_replace('/'sid=(''?'"?).*?''1/ism','');
$this->_replace('/'sclass=(''?'"?).*?''1/ism','');
// remove coments
$this->_replace('/<'!--.*?-->/ism','');
// remove script/style
$this->_replace('/<script[^>]*>.*?'/script>/ism','');
$this->_replace('/<style[^>]*>.*?'/style>/ism','');
// multiple 'n
$this->_replace('/'n{2,}/ism','');
// remove multiple <br/>
$this->_replace('/(<br's?'/?>){2}/ism','<br/>');
$this->_replace('/(<br's?'/?>'s*){3,}/ism','<br/><br/>');
//tables
$this->_replace('/<table[^>]*>/ism', '');
$this->_replace('/<'/table>/ism', '<br/>');
$this->_replace('/<(tr|td|th)[^>]*>/ism', '');
$this->_replace('/<'/(tr|td|th)[^>]*>/ism', '<br/>');
// wrap and close
}
private function _replace($pattern, $replacement, $limit=-1){
$this->html = preg_replace($pattern, $replacement, $this->html, $limit);
}
查看更多- https://code.google.com/p/phpmobilizer/
您可以使用正则表达式来删除css-script的标签和图像的标签,只需将这些代码替换为空白
preg_replace($pattern, $replacement, $string);
有关函数的详细信息,请访问:http://php.net/manual/en/function.preg-replace.php