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
これを試して、ニーズに合わせて調整してください。