下面是一个快速示例,说明如何使用 SimpleXML 解析器和 XPath。
// Get your page HTML string
$html = file_get_contents('1page.htm');
// To suppress invalid markup warnings
libxml_use_internal_errors(true);
// Create SimpleXML object
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
// Find a nodes
$blocks = $xml->xpath('//div[contains(@class, "product_detail_info_rating_stars")]');
foreach ($blocks as $block)
{
$count = 0;
foreach ($block->children() as $child) {
if ($child['class'] == 'product_detail_star full') {
$count++;
}
}
echo '<pre>'; print_r('Rating: ' . $count . ' of ' . $block->count()); echo '</pre>';
}
// Clear invalid markup error buffer
libxml_clear_errors();
对于这样的测试html页面:
<!doctype html>
<html>
<head></head>
<body>
<table>
<tr>
<td>
<div class="product_detail_info_rating_stars">
<div class="product_detail_star full"></div>
<div class="product_detail_star"></div>
<div class="product_detail_star"></div>
<div class="product_detail_star"></div>
<div class="product_detail_star"></div>
</div>
</td>
</tr>
<tr>
<td>
<div class="product_detail_info_rating_stars">
<div class="product_detail_star full"></div>
<div class="product_detail_star full"></div>
<div class="product_detail_star"></div>
<div class="product_detail_star"></div>
<div class="product_detail_star"></div>
</div>
</td>
</tr>
<tr>
<td>
<div class="product_detail_info_rating_stars">
<div class="product_detail_star full"></div>
<div class="product_detail_star full"></div>
<div class="product_detail_star full"></div>
<div class="product_detail_star full"></div>
<div class="product_detail_star"></div>
</div>
</td>
</tr>
</table>
</body>
</html>
它将输出如下内容:
Rating: 1 of 5
Rating: 2 of 5
Rating: 4 of 5
玩这个以适应您的需求。