0

how to get div class value using dom document

i need to echo this value 4,458 members

from the below code

< div class="mbs fcg">4,458 members< /div>

right now my orginal code is

$links = $dom->getElementsByTagName('div');

foreach ($links as $link){

echo $link->nodeValue;
echo $link->getAttribute('class');

}

how to target this particular class = mbc fcg ?

now with my present code i am getting all div values.

what changes i should do

splash58
  • 26,043
  • 3
  • 22
  • 34
only chande
  • 99
  • 2
  • 10
  • 3
    possible duplicate of [PHP XML/HTML DOM get CSS class attribute with whitespace](http://stackoverflow.com/questions/7465557/php-xml-html-dom-get-css-class-attribute-with-whitespace) – Jigar Jul 19 '15 at 06:09
  • It is unclear what you want: 1) you ask to target a `class value`. 2) You want to echo a `text-node` ... So, what do you actually want? – Ole Sauffaus Jul 19 '15 at 06:18
  • sir, what i want is
    4,458 members< /div> in this code i want to scrape this value 4,458 members
    – only chande Jul 19 '15 at 06:23
  • Duplicate http://stackoverflow.com/questions/4835300/php-dom-to-get-tag-class-with-multiple-css-class-name –  Jul 19 '15 at 07:10

3 Answers3

2

you will need to use DOMXPath, which will take a DOMDocument instance

$xpath   = new DOMXPath( $dom );
// if the className doesn`t changes
$members = $xpath->query( '//div[@class="mbs fcg"]' );
// if the class name changes ex. class="mbs fcg my-other class-name"
$members = $xpath->query( '//div[contains(@class,"mbs fcg")]' );

alternatively if you want to iterate all over your div`s you could try

$divs = $dom->getElementsByTagName( 'div' );
foreach( $divs as $div ){
    // if the className doesn`t changes
    if( $div->getAttribute( 'class' ) === 'mbs fcg' ){
        echo $div->nodeValue;
    }
    // if the class name changes ex. class="mbs fcg my-other class-name"
    if( strpos( $div->getAttribute( 'class' ), 'mbs fcg' ) !== false ){
        echo $div->nodeValue;
    }
}
Mujnoi Gyula Tamas
  • 1,759
  • 1
  • 12
  • 13
1

NOTICE::: THIS IS A JAVASCRIPT SOLUTION ... NOT A PHP DOMDOCUMENT SOLUTION

Try this HTML:

<div id="ME" class="mbs fcg">4,458 members</div>

... and this Javascript:

var WANTED_TEXT = document.getElementById('ME').firstChild.nodeValue;

EDIT2:

If you actually want, to get all textnodes from all occurrences of elements having class='mbs cfg' ... then try the following HTML:

<div class="mbs fcg">4,458 members</div>

... and this Javascript:

var Collection = document.getElementsByClassName('mbs fcg');

for(i=0; i<Collection.length; i++) {
    Texts = Collection[i].firstChild.nodeValue;
    document.write('<p>'+Texts+'</p>');
}

That should echo the pure text from all elements in the Collection.

Ole Sauffaus
  • 534
  • 3
  • 13
0

I think you need to use an id to target a single div, such as:

< div id="my_id_name" class="mbs fcg">4,458 members< /div>
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
uofarob
  • 65
  • 1
  • 12