-2

I want to get the content (only the number) of 'count-link' with php:

<div class="left">
<a class="count-link" href="http://url.com">
<span>22</span>
users
</a>
</div>

I have tried this, but it did not work:

$doc = new DomDocument();
$div = $doc->getElementByClass('count-link');
if($div) {
echo $div->textContent;
}
PeeHaa
  • 66,697
  • 53
  • 182
  • 254
Marc Ster
  • 2,236
  • 5
  • 28
  • 57

2 Answers2

1

This will work (tested):

<?php

function getTextBetweenTags($tag, $html, $strict=0)
{
    /*** a new dom object ***/
    $dom = new domDocument;

    /*** load the html into the object ***/
    if($strict==1)
    {
        $dom->loadXML($html);
    }
    else
    {
        $dom->loadHTML($html);
    }

    /*** discard white space ***/
    $dom->preserveWhiteSpace = false;

    /*** the tag by its tag name ***/
    $content = $dom->getElementsByTagname($tag);

    /*** the array to return ***/
    $out = array();
    foreach ($content as $item)
    {
        /*** add node value to the out array ***/
        $out[] = $item->nodeValue;
    }
    /*** return the results ***/
    return $out;
}

$html = '<div class="left">
<a class="count-link" href="http://url.com">
<span>22</span>
users
</a>
</div>';

//Example output array
print_r(getTextBetweenTags("span", $html));

//Example save in array
$myArr = getTextBetweenTags("span", $html);

//Example print text only
echo $myArr[0];

//Example save text only to var
$myText = $myArr[0];

?>
icecub
  • 7,964
  • 5
  • 34
  • 63
  • 1
    what do I have to insert for the tagname here? "span" ? And what do I insert for $html if i want the current file? – Marc Ster Sep 25 '14 at 10:11
  • I don't get what you mean? The tag name is "span" obviously. But what do you mean with current file? Do you want to process html that hasn't been outputted yet? In that case, isn't it easier to use regex? Edit: If you scroll the code down, there's an example use. – icecub Sep 25 '14 at 10:18
  • Added examples to the code. Scroll it down and you should find everything you can possible need. – icecub Sep 25 '14 at 10:29
-1
<div class="left">
<a class="count-link" href="http://url.com">
<span id= "span_value">22</span>
users
</a>
</div>

and

$doc = new DomDocument();
$div = $doc->getElementById('span_value');
if($div) {
echo $div->textContent;
}

I think this will work.

Naincy
  • 2,833
  • 1
  • 10
  • 21