如何构建正则表达式来提取<table>
的内容?我想刮一个网站,但不是第一个表,只有第二页。我这样做:
preg_match('/<table[^>]+cellspacing="0"[^>]*>(.*?)<'/table>', $returnCurl, $features);
HTML在这里
我只想要"features"表
我认为过早接受,如果你想使用DOMDocument做它,那么这里有一个通用的DOM废弃类,我之前建立的,它非常基本。如果你想要更多的功能,也有简单的HTML DOM,但底线是不要使用正则表达式来解析HTML!
<?php
$site = 'http://www.grossiste-informatique.com/grossiste/detail_article_popup.php?code_article=POA/F200CA-KX019H';
$scraper = new DOMScraper();
//Set site and get source
$scraper->setSite($site)
->setSource();
echo '<table cellspacing="0" cellpadding="3" border="0" width="100%">',
//match and return only tables inner content with cellpadding="3"
$scraper->getInnerHTML('table', 'cellpadding=3'),
'</table>';
/**
* Generic DOM scapper using DOMDocument and cURL
*/
Class DOMScraper extends DOMDocument{
public $site;
private $source;
private $dom;
function __construct(){
libxml_use_internal_errors(true);
$this->preserveWhiteSpace = false;
$this->strictErrorChecking = false;
$this->formatOutput = true;
}
function setSite($site){
$this->site = $site;
return $this;
}
function setSource(){
if(empty($this->site))return 'Error: Missing $this->site, use setSite() first';
$this->source = $this->get_data($this->site);
return $this;
}
function getInnerHTML($tag, $id=null, $nodeValue = false){
if(empty($this->site))return 'Error: Missing $this->source, use setSource() first';
$this->loadHTML($this->source);
$tmp = $this->getElementsByTagName($tag);
$ret = null;
foreach ($tmp as $v){
if($id !== null){
$attr = explode('=',$id);
if($v->getAttribute($attr[0])==$attr[1]){
if($nodeValue == true){
$ret .= trim($v->nodeValue);
}else{
$ret .= $this->innerHTML($v);
}
}
}else{
if($nodeValue == true){
$ret .= trim($v->nodeValue);
}else{
$ret .= $this->innerHTML($v);
}
}
}
return $ret;
}
function innerHTML($dom){
$ret = "";
$nodes = $dom->childNodes;
foreach($nodes as $v){
$tmp = new DOMDocument();
$tmp->appendChild($tmp->importNode($v, true));
$ret .= trim($tmp->saveHTML());
}
return $ret;
}
function get_data($url){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}else{
return file_get_contents($url);
}
}
}
?>
我会第一时间把你链接到相关文章
用DOMDocument代替。
同样,如果你真的想要(你真的不应该想要),你可以试试这个regex(未经测试):
preg_match('/<table[^>]+>.*?<table[^>]+>(.*?)<'/table>/is', $returnCurl, $features);