PHP 获取 html 源代码,然后解析某些 DIV 标签中的值


PHP to get html source, then parse values within certain DIV tags

我可以很好地获取源代码,但是我现在希望能够从特定的div中获取数据:

$html = file_get_contents('http://www.website.com');

假设$html包含:

<div class="productData">
   <div class="productDescription">Here is the product description</div>
   <div class="productPrice">1.99</div>
</div>

我希望能够返回 中的数据,并对所有出现的情况执行此操作?

谢谢。

使用 DOMDocument 类,结合 DOMXPath,如下所示:

$url = 'http://www.website.com/';
$dom = new DOMDocument();
$dom->load($url);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//*[contains(@class, 'productData')]");
foreach ($nodes as $node) {
    // do something
}