Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements by class name using DOMDocument

This question seems to have been answered numerous times but i still cant seem to put the pieces together.

I would like to get node value of every class by name. for example

<td class="thename"><strong>32</strong></td>
<td class="thename"><strong>12</strong></td>

i would like to grab the 32 and the 12. I assume this requires for sort of for loop but not sure exactly how to go about implementing it. Here's what i have so far

$domain = "http://domain.com";
$dom = new DOMDocument();

$dom->loadHTMLFile($domain);
$xpath = new DomXpath($dom);
$div = $xpath->query('//*[@class="thename"]')->item(0);
$stuff = $div ->textContent;

echo($stuff);
like image 441
Sammy Avatar asked Mar 03 '13 10:03

Sammy


2 Answers

i simply did this in php

$dom = new DOMDocument('1.0');
           $classname = "product-name";

           @$dom->loadHTMLFile("http://shophive.com/".$query);
           $nodes = array();
           $nodes = $dom->getElementsByTagName("div");
           foreach ($nodes as $element)
           {
               $classy = $element->getAttribute("class");
               if (strpos($classy, "product") !== false)
               {
                       echo $classy;
                       echo '<br>';
               }

           }
like image 124
Naveed Khan Avatar answered Oct 23 '22 11:10

Naveed Khan


Is this what your are looking for?

    $result = array();

    $doc = <<< HTML
    <html>
        <body>
            <div>1
                <span>2</span>
            </div>
            <div>3</div>
            <div>4
                <span class="class1"><strong>5</strong></span>
                <span class="class1"><strong>6</strong></span>
                <span>7</span>
            </div>
        </body>
    </html>
HTML;
    $classname = "class1";
    $domdocument = new DOMDocument();
    $domdocument->loadHTML($doc);
    $a = new DOMXPath($domdocument);
    $spans = $a->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

    for ($i = $spans->length - 1; $i > -1; $i--) {
        $result[] = $spans->item($i)->firstChild->nodeValue;
    }

    echo "<pre>";
    print_r($result);
    exit();
like image 32
user2112300 Avatar answered Oct 23 '22 10:10

user2112300