如何用Simple HTML DOM Parser获取指定DOM数据并修复代码问题?
问题解决:HTML数据提取与SQL插入
需求说明
从指定HTML结构中提取以下三类数据并组成数组,最终插入到SQL数据库中:
- a标签的
href属性值 - 类名为
siteLogo的li标签下img元素的src属性值 - h3标签的纯文本内容
目标HTML结构
<div class="siteList"><a href="https://test1.com" target="_blank" rel="noopener nofollow"><div class="badge" style="background:transparent; position:absolute;"><img src="/img/ran.png" width="30" height="30"></div><li class="siteLogo"><img src="/data1_250x70.png" alt width="250" height="auto" title></li><li class="siteInfo"><h3 style="color:#000;font-weight:bold;">TestSite 1</h3></li></a></div> <div class="siteList"><a href="https://test2.com" target="_blank" rel="noopener nofollow"><div class="badge" style="background:transparent; position:absolute;"><img src="/img/ran.png" width="30" height="30"></div><li class="siteLogo"><img src="/data2_250x70.png" alt width="250" height="auto" title></li><li class="siteInfo"><h3 style="color:#000;font-weight:bold;">TestSite 2</h3></li></a></div> <div class="siteList"><a href="https://test3.com" target="_blank" rel="noopener nofollow"><div class="badge" style="background:transparent; position:absolute;"><img src="/img/ran.png" width="30" height="30"></div><li class="siteLogo"><img src="/data3_250x70.png" alt width="250" height="auto" title></li><li class="siteInfo"><h3 style="color:#000;font-weight:bold;">TestSite 3</h3></li></a></div>
原代码问题
你编写的代码直接从div.siteList元素获取href、plaintext和src,但这些属性并不属于div元素,需要定位到对应的子元素才能正确提取数据:
$R = array(); foreach($html->find('div.siteList') as $element) { array_push($R,[$element->href,$element->plaintext,$element->src]); }
修正后的提取代码
假设你使用的是simple_html_dom库,修正代码如下,通过精准定位子元素来获取目标数据:
$R = array(); // 遍历每个siteList容器 foreach($html->find('div.siteList') as $container) { // 获取a标签的href属性 $href = $container->find('a', 0)->href; // 获取siteLogo下img的src属性 $logoSrc = $container->find('li.siteLogo img', 0)->src; // 获取h3标签的纯文本 $siteName = $container->find('h3', 0)->plaintext; // 将数据存入数组 $R[] = [$href, $logoSrc, $siteName]; }
插入SQL数据库示例
使用预处理语句插入数据,避免SQL注入风险,示例代码如下(假设使用PDO连接数据库):
// 假设已建立PDO数据库连接$pdo $sql = "INSERT INTO your_table_name (href, logo_src, site_name) VALUES (?, ?, ?)"; $stmt = $pdo->prepare($sql); // 遍历数组执行插入 foreach($R as $item) { $stmt->execute([$item[0], $item[1], $item[2]]); }
内容的提问来源于stack exchange,提问作者KOOLKOOLMAN
相关产品推荐
相关产品推荐

