这是另一种方法,当您想使用 PHP DOMDocument 类在 PHP 中获取/读取 HTML 元素时指示。
<?php
// string with HTML content
$strhtml = '<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Document Title</title>
</head>
<body>
<div id="dv1">www.MarPlo.net</div>
<div class="description">http://www.coursesweb.net</div>
</body></html>';
// create the DOMDocument object, and load HTML from a string
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
// gets all DIVs
$divs = $dochtml->getElementsByTagName('div');
// traverse the object with all DIVs
foreach($divs as $div) {
// if the current $div has class="description", gets and outputs content
if($div->hasAttribute('class') && $div->getAttribute('class') == 'description') {
$cnt = $div->nodeValue;
echo $cnt. '<br/>';
}
}
?>
您可以在 php.net 上找到有关 DOMDocument 的文档。