0

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?

4
  • 1
    $name is not a string and you can't echo it. Try print_r maybe to check? Commented Apr 28, 2019 at 5:45
  • Now with print_r($name), it's return "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65015808 bytes) in C:\xampp\htdocs\index.php on line 21" Commented Apr 28, 2019 at 5:49
  • You need to use $name->plaintext. Check PHP Simple Html Dom get the plain text of div Commented Apr 28, 2019 at 5:55
  • One thing to be very careful about is when using class attributes to find data, they can be easily changed by the page developers and suddenly your code fails to load this data. Commented Apr 28, 2019 at 6:57

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why you trying to use DomDocument when there is simpler why using Simple HTML that OP used it?
@Mohammad I have updated my solution for SImple HTML

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.