这是我从表中提取数据的代码。
但我想删除链接。
以及如何将标题和价格组合起来。
<?php
$ch = curl_init ("http://www.digionline.ir/Allprovince/CategoryProducts/cat=10301");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match('#<table[^>]*>(.+?)</table>#is', $page, $matches);
foreach ($matches as &$match) {
$match = $match;
}
echo '<table>';
echo $match ;
echo '</table>';
?>
最佳答案
我建议使用 HTML 解析器。使用 DOMDocument
+ DOMXpath
,无需安装,它们已经内置。示例:
$ch = curl_init ("http://www.digionline.ir/Allprovince/CategoryProducts/cat=10301");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($page);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$data = array();
// get all table rows and rows which are not headers
$table_rows = $xpath->query('//table[@id="tbl-all-product-view"]/tr[@class!="rowH"]');
foreach($table_rows as $row => $tr) {
foreach($tr->childNodes as $td) {
$data[$row][] = preg_replace('~[\r\n]+~', '', trim($td->nodeValue));
}
$data[$row] = array_values(array_filter($data[$row]));
}
echo '<pre>';
print_r($data);
$data
应包含:
Array
(
[0] => Array
(
[0] => AMDA4-3400
[1] => 1,200,000
[2] => 1,200,000
)
[1] => Array
(
[0] => AMDSempron 145
[1] => 860,000
[2] => 910,000
)
关于php - 使用curl和正则表达式获取表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618061/