我试过这段代码,
$html= file_get_contents("page.html");
$dom = new DOMDocument;
$dom->loadHTML($html);
$div = $dom->getElementsByClassName('mydiv1');
$result = $dom->saveHTML($div);
echo $result;
<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;
如何根据课程获取内容?
答案 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;