简体   繁体   中英

Get h2 html using Simple HTML DOM Parser

I have the HTML web page with this code:

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

Now I want to use Simple HTML DOM Parser to get the text value of h2 in this div. My code is:

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

But it always return an error: "

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

How can I fix this error?

Can you try for Simple HTML DOM

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

There are other methods to parse

Method 1.

You can get the H2 tags using the following code snippet, using DOMDocument and getElementsByTagName

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

Method2

Using the Xpath you can parse it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM