如何从带有 php DOM 的 html 页面获取特定的 link?

How to get specific link from a html page with php DOM?

我使用此代码获取 html 页面中的所有 link,它工作正常。

<?php
    $html = file_get_contents('http://realestate.com.kh/real-estate-for-sale-in/all/');

    $dom = new DOMDocument();
    @$dom->loadHTML($html);

    // grab all the on the page
    $xpath = new DOMXPath($dom);
    $hrefs = $xpath->evaluate("/html/body//a");

    for ($i = 0; $i < $hrefs->length; $i++) {
           $href = $hrefs->item($i);
           $url = $href->getAttribute('href');
           echo $url.'<br />';
    }
?>

但我只想从 div 或 class 中获取特定的 link 就像这样

<ul class="menu">
 <li><a href="#">product1</li>
 <li><a href="#">product2</li>
 <li><a href="#">product3</li>
 <li><a href="#">product4</li>
</ul>

那么我怎样才能把class给上面的代码,这样我就只能在菜单class中得到link。

非常感谢你帮我解决这个问题。

你应该可以做到

$xpath->query('/html/body/ul[contains(@class,"menu")]/a');

查看:PHP DOM Xpath - search for class name