3

我有一个html:

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

和代码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;
}

如何获得 2 td 的值但仅使用 1 foreach

4

2 回答 2

1

使用运算符将​​两个类放入逻辑 OR 表达式中|

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

这打印:

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

演示

于 2012-06-07T03:24:20.417 回答
0

尝试

$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 />';
}
于 2012-06-07T03:25:18.790 回答