Get string inside div in PHP

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 is inside this div and this needs to happen on the server side ... so what would be the best way to do this using php?     

asked by anonymous 03.03.2017 / 17:45

2 answers

1

As 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 echo would be the contents of div , including the span tag, as described in the question. But if the content you want is span , just change the tag name to:

$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
    
03.03.2017 / 17:57
1

Use the strip_tags () function together with trim (), it removes the String tags Ex:

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

var_dump($out);

Output will result in:

string(21) "435 itens encontrados"

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

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

Output:

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

Reference: strip_tags php manual .

    
03.03.2017 / 18:01