Hai Truong IT
Hai Truong IT

Reputation: 4187

How to get value using DOM HTML

I have a html:

$content = "
<tr>
   <td class="ttl"><a href="#">Colors</a></td>
   <td class="nfo">Dark Grey, Rose Red, Blue, Brown, Sand White</td>
</tr>";

And code php:

$dom = new DOMDocument();
@$dom->loadHTML($content);      
$xpath = new DOMXPath($dom);

$attbs = $xpath->query("//td[@class='ttl']");
foreach($attbs as $a) { 
    print $a->nodeValue;
}

$values = $xpath->query("//td[@class='nfo']");
foreach($values as $v) { 
    print $v->nodeValue;
}

How get value of 2 td but only using 1 foreach

Upvotes: 3

Views: 1106

Answers (2)

Hai Truong IT
Hai Truong IT

Reputation: 4187

try

$trs = $xpath->query("//tr");
foreach ($trs as $tr) {
    $attbs = $xpath->query("//td[@class='ttl']", $tr);
    $values = $xpath->query("//td[@class='nfo']", $tr);
    echo $attbs->item(0)->nodeValue . '-' .  $values->item(0)->nodeValue . '<br />';
}

Upvotes: 0

nickb
nickb

Reputation: 59699

Put both classes into a logical OR expression with the | operator:

$attbs = $xpath->query("//td[@class='ttl'] | //td[@class='nfo']");
foreach($attbs as $a) { 
    print $a->nodeValue;
}

This prints:

ColorsDark Grey, Rose Red, Blue, Brown, Sand White

Demo

Upvotes: 1

Related Questions