Catch string inside PHP div

Asked

Viewed 1,791 times

0

I have a variable that stores an HTML block:

$qtd = '<div id="itens">                
            <span>
                435 itens encontrados
            </span>
        </div>';

I need to get the text that’s inside this div and this needs to happen on the server-side...so what would be the best way to do this using php?

2 answers

1


Since this is a piece of HTML code, you can use the class DOMDocument:

$qtd = '<div id="itens">                
            <span>
                435 itens encontrados
            </span>
        </div>';

$doc = new \DOMDocument();
$doc->loadHTML($qtd);

$elements = $doc->getElementsByTagName("div");

echo $elements[0]->nodeValue;

In this way, the result of the echo would be the content of div, including the tag span, as described in the question. But if the desired content is span, just change the name of the tag in:

$doc->getElementsByTagName("div");
// -------------------------^

As follows:

$qtd = '<div id="itens"><span>435 itens encontrados</span></div>';

$doc = new \DOMDocument();
$doc->loadHTML($qtd);

$elements = $doc->getElementsByTagName("span");

echo $elements[0]->nodeValue;

The result will be:

435 itens encontrados
  • Very good! I’ll remember this forever now, thank you!

1

Use the strip_tags() function along with Trim(), it removes String Ex tags:

$out = trim(strip_tags($qtd));

var_dump($out);

The output will result in:

string(21) "435 itens encontrados"

If you want to keep the span tag, you can do it this way:

$out2 = trim(strip_tags($qtd, "<span>"));

Exit:

string(66) "<span>
            435 itens encontrados
           </span>"

Reference: strip_tags php manual.

  • Thank you for the reply, I tested here and also served me perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.