【发布时间】:2011-09-06 18:13:09
【问题描述】:
给定表单的一系列元素
<td class="name">Product Name</td>
<td class="price">$10.00</td>
可以使用 domdocument() 将包含 100 个名称/价格对的页面解析为一组 100 个名称和一组单独的 100 个价格。但是,如果缺少其中一个价格,则会得到一组 100 个名称和一组 99 个价格,并且不清楚哪个产品缺少其价格。
使用正则表达式解析成对的名称/价格数据(使价格可选)可以识别哪个产品缺少价格,因为结果是 100 对,其中一个具有空的价格值。有没有办法使用domdocument()来实现,这样就不需要使用regex来解析html了?
编辑:我尝试了 dqhendricks 的建议,但我在 foreach 循环中遇到语法错误,如下所示
<?php
$html = <<<EOT
<table>
<tr>
<td class="productname">a</td>
<td class="price">1</td>
</tr>
<tr>
<td class="productname">b</td>
<td class="price">2</td>
</tr>
<tr>
<td class="productname">c</td>
<td class="price">3</td>
</tr>
<tr>
<td class="productname">d</td>
<td class="price">4</td>
</tr>
<tr>
<td class="productname">e</td>
<td class="price">5</td>
</tr>
</table>
EOT;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadhtml($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//table/tr/') as $node) {
$name = $node->query('td[@class="productname"]');
$price= $node->query('td[@class="price"]');
}
print_r($node);
?>
【问题讨论】:
标签: php domdocument