我正在尝试使用以下代码将页面排序为表格中的格式,我需要能够将h4,span和非span提取到表格的名称,价格,项目中
<?php
$c = file_get_contents('http://www.bunnings.com.au/products_category_plumbing-supplies_1637.aspx');
$dom = new DOMDocument();
$dom->loadHTML($c);
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div[@class="details"]');
$div = $div->item(0);
echo $dom->saveXML($div);
?>
答案 0 :(得分:2)
这个简单的例子将名称,价格和项目编号放在表格中:
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div[@class="details"]');
echo '<table>';
foreach($div as $details)
{
$name = $details->getElementsByTagName('h4')->item(0)->getElementsByTagName('a')->item(0)->nodeValue;
$price = $details->getElementsByTagName('p')->item(0)->getElementsByTagName('span')->item(0)->nodeValue;
$itemNumber = $details->getElementsByTagName('p')->item(0)->childNodes->item(2)->nodeValue;
$html = '<tr>';
$html .= '<td>' . htmlspecialchars($name) . '</td>';
$html .= '<td>' . htmlspecialchars($price) . '</td>';
$html .= '<td>' . htmlspecialchars($itemNumber) . '</td>';
$html .= '</tr>';
echo $html;
}
echo '</table>';