PHP:按类名获取DOM元素

时间:2016-11-19 22:59:40

标签: php html dom

我有以下内容:

<div id="content">
<div class="content-top">bla</div>
<div class="inner text-inner">
bla bla bla
</div>
</div>

和PHP:

 $page = file_get_contents('http://www.example.com/test');
 @$doc = new DOMDocument();
 @$doc->loadHTML($page);
 $node = $doc->getElementById('content');

如何修改$node = $doc->getElementById('content');以便我可以定位<div class="inner text-inner">

1 个答案:

答案 0 :(得分:6)

您可以使用XPath轻松实现它。

$page = file_get_contents('http://www.example.com/test');
@$doc = new DOMDocument();
@$doc->loadHTML($page);   

$xpath = new DomXPath($doc);

$nodeList = $xpath->query("//div[@class='inner text-inner']");
$node = $nodeList->item(0);

// To check the result:
echo "<p>" . $node->nodeValue . "</p>";

这将输出:

bla bla bla