使用简单 HTML DOM 解析器获取 h2 html

Get h2 html using Simple HTML DOM Parser

我有 HTML 网页,代码如下:

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

现在我想使用Simple HTML DOM Parser 来获取这个div 中h2 的文本值。 我的代码是:

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

但它总是 return 一个错误:“

Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 21
Array

我该如何解决这个错误?

你能试试 Simple HTML DOM

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

还有其他方法解析

方法一.

您可以使用以下代码片段获取 H2 标签,使用 DOMDocumentgetElementsByTagName

$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;
}