这并不难,真的……只要谷歌,然后点击这个链接,你现在知道如何解析一个 DOM,在这里你可以看到你可以使用哪些方法来选择所有感兴趣的元素,迭代 DOM,获取它的内容和你有什么...
$DOM = new DOMDocument();
$DOM->loadHTML($htmlString);
$spans = $DOM->getElementsByTagName('span');
for ($i=0, $j = count($spans); $i < $j; $i++)
{
echo $spans[$i]->childNodes[0]->nodeValue.' - '.$spans[$i]->parentNode->nodeValue."\n";
}
如果我没记错的话,这似乎就是你所追求的。这只是我的想法,但我认为这应该输出如下内容:
Case Size: - 44mm
Case Thickness: - 13mm
更新:
这是一个经过测试的解决方案,如果我没记错的话,它会返回所需的结果:
$str = "<div id='productDetails' class='tabContent active details'>
<span>
<b>Case Size:</b>
</span>
44mm
<br>
<span>
<b>Case Thickness:</b>
</span>
13mm
<br>
<span>
<b>Water Resistant:</b>
</span>
5 ATM
<br>
<span>
<b>Brand:</b>
</span>
Fossil
<br>
<span>
<b>Warranty:</b>
</span>
11-year limited
<br>
<span>
<b>Origin:</b>
</span>
Imported
<br>
</div>";
$DOM = new DOMDocument();
$DOM->loadHTML($str);
$txt = implode('',explode("\n",$DOM->textContent));
preg_match_all('/([a-z0-9].*?\:).*?([0-9a-z]+)/im',$txt,$matches);
//or if you don't want to include the colon in your match:
preg_match_all('/([a-z0-9][^:]*).*?([0-9a-z]+)/im',$txt,$matches);
for($i = 0, $j = count($matches[1]);$i<$j;$i++)
{
$matches[1][$i] = preg_replace('/\s+/',' ',$matches[1][$i]);
$matches[2][$i] = preg_replace('/\s+/',' ',$matches[2][$i]);
}
$result = array_combine($matches[1],$matches[2]);
var_dump($result);
//result:
array(6) {
["Case Size:"]=> "44mm"
["Case Thickness:"]=> "13mm"
["Water Resistant:"]=> "5"
["ATM Brand:"]=> "Fossil"
["Warranty:"]=> "11"
["year limited Origin:"]=> "Imported"
}
要将其插入您的数据库:
foreach($result as $key => $value)
{
$stmt = $pdo->prepare('INSERT INTO your_db.your_table (meta_key, meta_value) VALUES (:key, :value)');
$stmt->execute(array('key' => $key, 'value' => $value);
}
编辑
要完全捕获11-year limit
子字符串,您需要像这样编辑上面的代码:
//replace $txt = implode('',explode("\n",$DOM->textContent));etc... by:
$txt = $DOM->textContent;//leave line-feeds
preg_match_all('/([a-z0-9][^:]*)[^a-z0-9]*([a-z0-9][^\n]+)/im',$txt,$matches);
for($i = 0, $j = count($matches[1]);$i<$j;$i++)
{
$matches[1][$i] = preg_replace('/\s+/',' ',$matches[1][$i]);
$matches[2][$i] = preg_replace('/\s+/',' ',$matches[2][$i]);
}
$matches[2] = array_map('trim',$matches[2]);//remove trailing spaces
$result = array_combine($matches[1],$matches[2]);
var_dump($result);
输出是:
array(6) {
["Case Size"]=> "44mm"
["Case Thickness"]=> "13mm"
["Water Resistant"]=> "5 ATM"
["Brand"]=> "Fossil"
["Warranty"]=> "11-year limited"
["Origin"]=> "Imported"
}