如何根据类提取div内的内容?

时间:2015-02-27 07:12:57

标签: php html dom

我试过这段代码,

$html= file_get_contents("page.html");
$dom = new DOMDocument;
$dom->loadHTML($html);
$div = $dom->getElementsByClassName('mydiv1');
$result = $dom->saveHTML($div);
echo $result;

page.html中

<html>
<body>
<div id="test">
<div class="mydiv1">Hello</div>
<div class="mydiv2">How are you</div>
</div>
</body>
</html>

但是当我尝试使用它的作品时。等,

$html= file_get_contents("page.html");
$dom = new DOMDocument;
$dom->loadHTML($html);
$div = $dom->getElementById('test');
$result = $dom->saveHTML($div);
echo $result;

如何根据课程获取内容?

2 个答案:

答案 0 :(得分:1)

getElementsByClassName中没有实际的DOMDocument(但),但使用DOMXpath可以生成相同的结果:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$nodes= $finder->query('//div[@class="mydiv1"]');

答案 1 :(得分:1)

试试这段代码,

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div[@class="mydiv1"]');
$div = $div->item(0);
$result = $dom->saveXML($div);
echo $result;