使用 Simple HTML DOM Parser获取 h2 html



>我有包含以下代码的HTML网页:

<div class="col-sm-9 xs-box2">
    <h2 class="title-medium br-bottom">Your Name</h2>
</div>

现在我想使用简单的HTML DOM解析器来获取这个div中h2的文本值。我的代码是:

$name = $html->find('h2[class="title-medium br-bottom"]');
echo $name;

但它总是返回一个错误:">

Notice: Array to string conversion in C:xampphtdocsindex.php on line 21
Array

如何修复此错误?

你能试试Simple HTML DOM

 foreach($html->find('h2') as $element){
    $element->class;
 }

还有其他方法可以解析

方法 1.

您可以使用以下代码片段、DOMDocumentgetElementsByTagName 来获取 H2 标记

$received_str = '<div class="col-sm-9 xs-box2">
  <h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
@$dom->loadHTML($received_str);
$h2tags = $dom->getElementsByTagName('h2');
foreach ($h2tags as $_h2){
  echo $_h2->getAttribute('class');
  echo $_h2->nodeValue;
}

方法2

使用Xpath您可以解析它

$received_str = '<div class="col-sm-9 xs-box2">
    <h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
$dom->loadHTML($received_str);
$xpath = new DomXPath($dom);
$nodes = $xpath->query("//h2[@class='title-medium br-bottom']");
header("Content-type: text/plain");
foreach ($nodes as $i => $node) {
    $node->nodeValue;
}

最新更新